Home  >  Article  >  Web Front-end  >  How to stop setInterval

How to stop setInterval

DDD
DDDOriginal
2023-12-11 11:39:252083browse

You can use the clearInterval function to stop the timer created by the setInterval function. The setInterval function returns a unique timer ID, which can be passed as a parameter to the clearInterval function to stop the execution of the timer.

How to stop setInterval

In JavaScript, you can use the clearInterval function to stop the timer created by the setInterval function. The setInterval function returns a unique timer ID, which you can pass as a parameter to the clearInterval function to stop the timer execution.

The following is an example of using setInterval and clearInterval to stop a timer:

// 创建定时器,每1秒执行一次
const intervalId = setInterval(() => {
  console.log('定时器正在执行...');
}, 1000);
// 5秒后停止定时器
setTimeout(() => {
  clearInterval(intervalId); // 通过定时器ID停止定时器的执行
  console.log('定时器已停止');
}, 5000);

In the above example, the setInterval function will execute the callback function every 1 second and return the timer ID Assign a value to the intervalId variable. Then, through the setTimeout function, call the clearInterval function after 5 seconds and pass in the intervalId as a parameter to stop the execution of the timer.

When the clearInterval function is called, the timer will stop executing and the callback function will not be executed repeatedly.

It should be noted that the timer ID is unique, and each timer has its own ID. Therefore, make sure that when calling the clearInterval function, you pass the correct timer ID to stop a specific timer.

The above is the detailed content of How to stop setInterval. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn