This is what I'd like to do:
This is what I've tried
var clicked = false;
$('#button').click(function(){
A();
});
function A(){
clicked = true;
setTimeout(function(){
clicked == false;
)}, 1000);
setTimeout(function(){
if ( clicked == false ) {
B();
}
)}, 1000);
}
I think the code will for scenario 1 and 2 , but how can I get it working for 3 too?
EDIT: Just saw a related SO question upon posting which I didn't find through search. Please wait while I check if it's a duplicate
I think you are looking to throttle (buffer) the clicks, that is, you want to wait a specified amount of time before you act, if the same event happens again within your throttling period, you restart your wait. http://jsfiddle.net/8QdLV/
function B() {
console.log('Clicked')
}
var timeoutId;
$('#button').click(function() {
clearTimeout(timeoutId);
timeOutId = setTimeout(B, 1000);
});
This can be generalized http://jsfiddle.net/8QdLV/
function throttle(handler, buffer) {
var timeoutId;
buffer = buffer || 1000;
return function(e) {
clearTimeout(timeoutId);
var me = this;
timeoutId = setTimeout(function() {
handler.call(me, e);
}, buffer);
}
}
$('button').click(throttle(function() {
console.log('Throttled click');
});
By the way, you may want to use https://code.google.com/p/jquery-debounce/ which also provides a $.throttle
function
use the setInterval
function.
note that it doesn't suffice to record the click with a boolean, otherwise two clicks at t=0
, t=0.99
will both be cleared by the reset operation at t=1
.
var clicked = false
, hnd_reset = null
, hnd_check = null;
$('#button').click(function() {
A();
});
function A(){
clicked = true;
hnd_reset = setTimeout(function(){
clicked = false;
hnd_reset = null;
)}, 1000);
if (hnd_check === null) {
hnd_check = setInterval(function(){
if ( !clicked && (hnd_reset === null)) {
clearInterval( hnd_check );
hnd_check = null;
B();
}
)}, 1000);
}
}
alternatively you could track the number of clicks in an int starting at 0, allowing for execution of B
iff the tracker is 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.