如何取消函数内的超时



如何取消函数内的超时

这是我试过的

将超时设置为变量,然后清除它

如果我在这里做错了什么,请告知

var timer1 = null;
var timer2 = null;

function pointsLoop() {
for (let i = 0; i <= pointsList.length; i++) {
let point = pointsList[i]
timer1 = setTimeout(function timer() {
point.click()
point.classList.add("active");
}, i * 3000);
timer2 = setTimeout(function timer() {
point.classList.remove("active");
if (i == pointsList.length) {
i = 0
}
}, (i * 3000) + 3000);
}
}

$(".savemomery").click(
function () {
clearTimeout(timer1);
clearTimeout(timer2);
}
);

我会将所有超时存储在一个数组中,然后通过循环这个数组一次取消它们。

像这样:

let timeoutsArray = [];

function pointsLoop() {
for (let i = 0; i <= pointsList.length; i++) {
let point = pointsList[i]
timeoutsArray.push( setTimeout(function timer() {
point.click()
point.classList.add("active");
}, i * 3000));
timeoutsArray.push( setTimeout(function timer() {
point.classList.remove("active");
if (i == pointsList.length) {
i = 0
}
}, (i * 3000) + 3000));
}
}
$(".savemomery").click(function() {
for(let timeout of timeoutsArray) {
clearTimeout(timeout);
}
timeoutsArray = [];
});

最新更新