问题
I'm not quite sure of the mechanics of this problem, but I'm trying to have a single setTimeout set to a variable ID that I can easily cancel using clearTimeout. But, if setTimeout gets triggered twice before clearTimeout, things go wacky.
Example: http://www.w3schools.com/js/tryit.asp?filename=tryjs_settimeout2
Clicking "Try It" twice and then "Stop the Alert" twice, the function of set timeout still gets called. Likewise, I'm not sure why Try It would trigger the function twice considering the event is saved to a variable that is getting overwritten.
Any idea of what's going on here?
回答1:
Like MCL has explained, you're loosing the reference to previous timeout, since a new assignment will override it.
What you can do is to put the timeouts to an array:
var myTimer = [];
function myFunction () {
myTimer.push(setTimeout(function(){alert("Hello")},3000));
}
function myStopFunction () {
clearTimeout(myTimer.pop());
}
This way you can cancel the last set timeout when clicking Stop the alert
button.
A live demo at jsFiddle.
来源:https://stackoverflow.com/questions/17199498/cancel-multiple-timeouts-set-to-an-id