Cancel multiple timeouts set to an ID

邮差的信 提交于 2020-01-14 01:38:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!