问题
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 new timeout.
Demonstration code:
<div id='a'>lorem</div>
$('#a').click(function(){
//code to clear previous timeout
//This is not working: clearTimeout(timeout);
var timeout = setTimeout(function(){
//do something
},5000);
return timeout;
})
The only way I can think of is make timeout
global, but global is ugly.
Is there any better way to do this? And in the above codes, where is timeout
being returned to? In which scope I can use it?
回答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));
})
来源:https://stackoverflow.com/questions/29416999/how-to-store-and-reuse-a-timeout-in-a-jquery-event-handler