Check If A Button "hasn't" Been Clicked Within A Certain Amount Of Time (jquery)
Basically: You click a button and it runs function 1. If you don't click the button again within 1 second then function 2 runs. If you click the button within 1 second then it runs
Solution 1:
You'll want to use a timer to keep track of the time. You can use setTimeout
to run function 2 in 1 second (1000ms). If, however, you click button again, you should stop the timer. You can do that using clearTimeout
.
The core lines would be:
var timer;
// in button's click handler:clearTimeout(timer);
timer = setTimeout(function2, 1000);
Solution 2:
from the top of my head (haven't tested this, but this seems most logic to me):
var t = null;
$("button").click(function() {
console.log("this is function 1");
if (t !== null) { window.clearTimeout(t); }
t = window.setTimeout(function() {
console.log("and this is function 2");
}, 1000);
});
Solution 3:
This should do it:
(function() {
var timer = null;
$('#button').on('click', function() {
function1(); // always call function1clearTimeout(timer); // clear the timer
timer = setTimeout(function2, 1000); // run function2 1s later
});
})();
See http://jsfiddle.net/alnitak/QZRTA/
The outer function block serves to keep the timer
variable in the local scope without creating a global variable.
Solution 4:
Using setTimeout
and clearTimeout
:
var t = null;
var timeoutMs = 1000; // in ms
$("#btn1").click(function (){
func1();
if (t !== null)
clearTimeout(t);
t = setTimeout(func2, timeoutMs);
});
Solution 5:
$('button').click(function() {
console.log('Func 1');
clearTimeout($(this).data('throttle'));
$(this).data('throttle', setTimeout(function() {
console.log('Func 2');
}, 1000));
});
Post a Comment for "Check If A Button "hasn't" Been Clicked Within A Certain Amount Of Time (jquery)"