gpt4 book ai didi

Javascript clearTimeout() 不工作

转载 作者:行者123 更新时间:2023-11-30 08:27:02 24 4
gpt4 key购买 nike

当我尝试 clearTimeout() 时,超时只是继续。代码:

function autoSlides(x) {
var timeOut;
if (x == 1) {
plusSlides(1);
document.getElementById("switch").onclick = function () { autoSlides(2) };
timeOut = setTimeout(function () { autoSlides(1) }, 4000);
} else if (x == 2) {
clearTimeout(timeOut);
document.getElementById("switch").onclick = function () { autoSlides(1) };
}
}

最佳答案

那是因为您在函数内部声明了 timeOut。这意味着您使用的不是您之前认为保存的相同值。

function autoSlides(x) {
var timeOut; // Initialized to `undefined`
if (x === 1) {
timeOut = setTimeout(function() {
console.log('Look, the timeout finished');
}, 1000);
} else if (x === 2) {
// Remember: this is a new timeout variable
// So this really means `clearTimeout(undefined)`
clearTimeout(timeOut);
}
}

autoSlides(1);
autoSlides(2);

您需要做的是将超时 ID 保存在函数之外的某处。

var timeOut; // Won't be reset every time the function is called
function autoSlides(x) {
if (x === 1) {
timeOut = setTimeout(function() {
console.log('Look, the timeout never finishes');
}, 1000);
} else if (x === 2) {
// The value was saved last time
clearTimeout(timeOut);
console.log('cleared the timeout');
}
}

autoSlides(1);
autoSlides(2);

关于Javascript clearTimeout() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43944072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com