开发者

count the number of click in an interval of time

how can I count the number of clicks in a time interval, for instace: how many clicks the user did in 2 second开发者_StackOverflows?? I know how to count clicks but I don't know how to measeure time

Thanks


Try using a timeout to clear the function that detects the clicks. With jQuery, try this:

var clicks=0;
function myClickFunction(event){
    clicks++;
}
$(function(){
    $("#something").bind("click",myClickFunction);
    setTimeout(function(){
        $("#something").unbind("click",myClickFunction);
        alert("You clicked "+clicks+" times.");
    },2000);
});

Replace #something with a jQuery selector of an element you want the clicks to be detected on and the alert line with your own code that will be run after the timer has run out. Ad@m


HTML:

<button>Click me!</button>
<div id="status">Not Running</div>

JS:

var running = false,
    count = 0,
    run_for = 2000;

var end_counter = function() {
    if (running) {
        running = false;
        $("#status").text("Not Running");
        alert(count);
        started_at = 0;
    }
};
$('button').click(function() {
    if (running) {
        count++;
    } else {
        running = true;
        $("#status").text("Running");
        count = 1;
        setTimeout(end_counter, run_for);
    }
});

Demo: http://jsfiddle.net/pXMxQ/2/


define a variable 
attach click handler to element 
set variable = 0
start ur timer (setTimeout)
increment variable on each click
when timeout handler excutes, detach ur handler

- OR - 

define a variable for counter
define a variable for doCounting
set counter = 0, doCounting = true
start ur timer (setTimeout)
increment counter on each click if doCounting is true
set doCounting = false when timeout handler executes


Use the setTimeout function

e.g. if Every click increments a variable clickcount you could do the following:

 function startCounting(){
    clickcount = 0;
    setTimeout(function(){alert("you made "+clickcount +" clicks!");}, 2000);
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜