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?