How To Store And Reuse A Timeout In A Jquery Event Handler?
I have a button, when clicked it will start a timeout function, if it is clicked again before the function is executed, I want the former timeout to be cleared thus it can start a
Solution 1:
There are two alternatives to global variables that you can use here :
1 an IIFE creating a local scope :
(function(){
var timer;
$('#a').click(function(){
clearTimeout(timer);
timer = setTimeout(function(){
//do something
},5000);
})
})();
2 jquery data attached to the element
$('#a').click(function(){
clearTimeout($(this).data('timer'));
$(this).data('timer', setTimeout(function(){
//do something
},5000));
})
Post a Comment for "How To Store And Reuse A Timeout In A Jquery Event Handler?"