简体   繁体   English

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

[英]Why clearInterval is not working in my script?

I have got a problem with my clearInterval method. 我的clearInterval方法有问题。 I learn about JS in depth at FrontendMasters and there is an exercise where you need to use setInterval and log a string at every second and then run clearInterval after 5 seconds. 我在FrontendMasters上深入了解了JS,并且有一个练习,您需要使用setInterval并每秒记录一个字符串,然后在5秒钟后运行clearInterval。 I have access to the right solution but I would like to know why my solution is not working to get better understanding. 我可以使用正确的解决方案,但是我想知道为什么我的解决方案无法有效地理解。 The console.log('clear called', func); console.log('clear called', func); runs after 5 seconds and log the clear called string and the function body. 5秒钟后运行,并记录clear called字符串和函数体。 I have tried to use setTimeout to wrap wrapper.stop() but it did not work that way either. 我试图使用setTimeout来包装wrapper.stop()但它也不以这种方式工作。 I have used closures to try to solve the exercise. 我已经使用闭包来尝试解决该练习。 Here is my script. 这是我的剧本。

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();

Thanks 谢谢

clearInterval does not take a function but a timer id which gets returned when using setInterval (so that you can set multiple timers onto the same function, and cancel them individually). clearInterval不带功能,而是使用setInterval时返回的计时器ID (以便您可以将多个计时器设置到同一功能上,并分别取消它们)。 To use that, declare a local variable inside everyXsecsForYsecs 要使用它,请在everyXsecsForYsecs声明一个局部变量

  var timer;

Then assign the timer to it: 然后为其分配计时器:

 timer = setInterval(func, interval);

Then you can clearInterval(timer) . 然后,您可以clearInterval(timer)

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

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