Stop setInterval call in JavaScript

前端 未结 16 1791
星月不相逢
星月不相逢 2020-11-21 05:00

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the us

16条回答
  •  囚心锁ツ
    2020-11-21 05:44

    The clearInterval() method can be used to clear a timer set with the setInterval() method.

    setInterval always returns a ID value. This value can be passed in clearInterval() to stop the timer. Here is an example of timer starting from 30 and stops when it becomes 0.

      let time = 30;
      const timeValue = setInterval((interval) => {
      time = this.time - 1;
      if (time <= 0) {
        clearInterval(timeValue);
      }
    }, 1000);
    

提交回复
热议问题