簡體   English   中英

為什么clearInterval在我的腳本中不起作用?

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

我的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM