最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to detect clicks count within 5 seconds - Stack Overflow

programmeradmin1浏览0评论

I want to count mouse clicks on anywhere of page with jQuery.

If user clicks more than 10 click within 5 second I want to give a message.

Time counter will be checked elapsed time on every last click.

I'll use this code to prevent unwanted network traffic on my site. Because, I have a calender on page; every click of calender gets too many data (event/news lists) from server. If user click too much, it may block my site.

I want to count mouse clicks on anywhere of page with jQuery.

If user clicks more than 10 click within 5 second I want to give a message.

Time counter will be checked elapsed time on every last click.

I'll use this code to prevent unwanted network traffic on my site. Because, I have a calender on page; every click of calender gets too many data (event/news lists) from server. If user click too much, it may block my site.

Share Improve this question edited Nov 25, 2011 at 14:39 Nuri Akman asked Nov 25, 2011 at 13:25 Nuri AkmanNuri Akman 8203 gold badges19 silver badges41 bronze badges 2
  • 4 And what did you try already? – Bas Slagter Commented Nov 25, 2011 at 13:26
  • 3 May I ask why this question is getting downvoted? There isnt really a reason for that. Its a proper question, and if you do it because he didnt post his code. just ask him for it... – Teun Pronk Commented Nov 25, 2011 at 13:36
Add a ment  | 

5 Answers 5

Reset to default 8

Mouse clicks (except those ones which propagation is stopped) are bubbling, so you can just listen live clicks on document.body.

Then, you should keep an array, where you store last 10 clicks timestamps (when length is 10, just remove first one before pushing new one). Check first and last timestamp delta, thats it.

You could do:

var numberOfClicks= [];

$(document).click(function(e){
    if(numberOfClicks.length < 10){
       numberOfClicks.push(new Date().getTime());
    }else{
        var diff = numberOfClicks[numberOfClicks.length -1] - numberOfClicks[0];
        console.log(diff);
        if(diff < 5000){
            //alert("toomany!");
            e.preventDefault();
         }
        numberOfClicks.shift();
        numberOfClicks.push(new Date().getTime());     
        console.log(numberOfClicks);
    }
});

Fiddle here http://jsfiddle/WWpqZ/

EDIT - this code doesn't consider the time you spent watching the alert and clicking ok

var numberOfClicks= [];
alertTime = 0;
$(document).click(function(){
    if(numberOfClicks.length < 10){
       numberOfClicks.push(new Date().getTime());
    }else{

        var diff = numberOfClicks[numberOfClicks.length -1] - numberOfClicks[0] - alertTime;

        if(diff < 5000){
            var beforeAlert = new Date().getTime();
            alert("toomany!");
            var afterAlert = new Date().getTime();
            alertTime = afterAlert - beforeAlert;
         }
        numberOfClicks.shift();
        numberOfClicks.push(new Date().getTime());     

    }
});

fiddle here http://jsfiddle/WWpqZ/1/

what about this:

$(document).ready(function () {

  var amountOfClicks = 0;
  window.setInterval("resetClicks()", 5000);


  $('body').click(function(){
     amountOfClicks++;
     if(amountOfClicks > 10){
alert('You clicked more than 10 times the last 5 seconds');
resetClicks();
}
  });

});

function resetClicks(){
  amountOfClicks = 0;
}

This is my "improved" version:

var tOuts = [];
$(document).click(function(){
    tOuts.push( setTimeout(function(){
        tOuts.shift();
    }, 5000) );

    if (tOuts.length == 10) {
        // clear all the timeouts
        for (x in tOuts) { clearTimeout(tOuts[x]); }
        tOuts = [];
        callback();
    }
});


callback = function(){
    alert('you have clicked 10 times within 5 seconds');
}

What it does is:

for each click on the page it adds timeout to the tOuts array. When 5 seconds have been passed since the click - the element from the array is being removed, so the count of the elements in the array is the total clicks the user have made in the 5 seconds interval since the last click.

After the count reaches 10 all the timeouts are being cleared and the callback is being executed, so in order to execute the callback again - the user will have to make 10 more clicks.

jsFiddle Example

In vanilla JavaScript:

// Click listener
document.addEventListener("click", clickListener, false);
var counting = 0,
    clicks = 1;
function clickListener(e) {
    // Count the number of clicks
    clicks++;
    if (!counting) {
        counting = 1;
        setTimeout(function() {
            if (clicks > 9) {
                alert('Multiple clicks! ('+clicks+')');
            }
            counting = 0;
            clicks = 0;
        }, 5000);
    }
}

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>