Reputation: 895
how can I count the number of clicks in a time interval, for instace: how many clicks the user did in 2 seconds?? I know how to count clicks but I don't know how to measeure time
Thanks
Upvotes: 2
Views: 3122
Reputation: 10940
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);
}
Upvotes: 0
Reputation: 222388
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/
Upvotes: 1
Reputation: 2049
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
Upvotes: 1
Reputation: 7009
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
Upvotes: 0