简体   繁体   English

我对setTimeout / clearTimeout有问题

[英]I have issue with setTimeout/clearTimeout

I have following js 我有以下js

 document.addEventListener("DOMContentLoaded", function() { document.querySelector("#pageRedirect").addEventListener("change", changeHandler); }); function changeHandler() { var timer; if (pageRedirect.checked) { timer = setTimeout(function() { window.location.href = 'http://www.google.com'; }, 3000); console.log(pageRedirect.checked); } else { //dont redirect clearTimeout(timer); console.log(pageRedirect.checked); } } 
 <input type="checkbox" id="pageRedirect" name="pageRedirect" /> 

I dont redirect when checkbox uncheck but it is. 取消选中复选框时,我不重定向,但确实如此。 Where's my fault ? 我的错在哪里?

Thanks. 谢谢。

The issue is the location of your variable declaration for the timer ID. 问题是计时器ID的变量声明的位置。 It's inside your function, so when you attempt to clear it, it's not got the ID you assigned in the setTimeout . 它在函数内部,因此当您尝试清除它时,没有在setTimeout分配的ID。 You need to move the declaration outside of your function so it can keep the handle of the timer between invocations: 您需要将声明移出函数之外,以便可以在调用之间保留计时器的句柄:

var timer;
function changeHandler(){
    // etc

This is compounded by the spec for clearTimeout which says: clearTimeout 的规范进一步说明了这一点:

If handle does not identify an entry in the list of active timeouts of the WindowTimers object on which the method was invoked, the method does nothing. 如果handle未在调用该方法的WindowTimers对象的活动超时列表中标识一个条目,则该方法不执行任何操作。

IE it will silently ignore any invalid timer handles, which in your case would be undefined . IE会默默地忽略任何无效的计时器句柄,在您的情况下这些计时器句柄将是undefined

The issue is that the timer variable is redeclared every time the function executes, so even having closures, the viariable doesn't hold the timer. 问题在于,每次函数执行时都会重新声明timer变量,因此,即使有闭包,viariable也无法保存定时器。

You could store the timer somewhere else, like in the node. 您可以将计时器存储在其他位置,例如在节点中。 Notice in the following snippet I store the timer in this.timer 请注意,在以下代码片段中,我将计时器存储在this.timer

 document.addEventListener("DOMContentLoaded", function () { document.querySelector("#pageRedirect").addEventListener("change", changeHandler); }); function changeHandler(){ if(pageRedirect.checked){ this.timer = setTimeout(function(){ document.getElementById('output').innerHTML = "done"; }, 3000); } else { //dont redirect clearTimeout(this.timer); } } 
 <input type="checkbox" id="pageRedirect" name="pageRedirect"/> <div id="output"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM