gpt4 book ai didi

javascript - 为什么clearInterval 在我的脚本中不起作用?

转载 作者:行者123 更新时间:2023-12-01 01:05:33 26 4
gpt4 key购买 nike

我的clearInterval方法有问题。我在 FrontendMasters 上深入了解了 JS,并且有一个练习,您需要使用 setInterval 并每秒记录一个字符串,然后在 5 秒后运行clearInterval。我可以获得正确的解决方案,但我想知道为什么我的解决方案无法更好地理解。 console.log('clear called', func); 会在 5 秒后运行并记录 clear called 字符串和函数体。我尝试使用 setTimeout 来包装 wrapper.stop() 但它也不起作用。我尝试使用闭包来解决这个练习。这是我的脚本。

function sayHowdy() {
console.log('Howdy');
}


function everyXsecsForYsecs(func, interval, totalTime) {
function clear() {
console.log('clear called', func);
clearInterval(func);
}
return {
start() {
setInterval(func, interval);
},
stop() {
setTimeout(clear, totalTime);
}
}
}


const wrapper = everyXsecsForYsecs(sayHowdy, 1000, 5000);
wrapper.start();
wrapper.stop();

谢谢

最佳答案

clearInterval 不接受函数,而是使用 setInterval 时返回的计时器 ID(以便您可以在相同的功能,并单独取消)。要使用它,请在 everyXsecsForYsecs

中声明一个局部变量
  var timer;

然后为其分配计时器:

 timer = setInterval(func, interval);

然后您可以clearInterval(timer)

关于javascript - 为什么clearInterval 在我的脚本中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55677770/

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