Home >Web Front-end >JS Tutorial >How to Use `setInterval` and `clearInterval` for Controlled Function Execution?

How to Use `setInterval` and `clearInterval` for Controlled Function Execution?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 00:30:09945browse

How to Use `setInterval` and `clearInterval` for Controlled Function Execution?

How to Control Intervals with setInterval and clearInterval

In the context of handling keyboard events, a question arises about the appropriate use of setInterval and clearInterval for managing the execution of a function. Let's explore the differences between these methods.

setInterval: Setting Up Recurring Timers

setInterval establishes a timer that executes a function repeatedly at a specified interval in milliseconds. For example, the following code sets up a timer to call the drawAll() function every 20 milliseconds:

setInterval(drawAll, 20);

However, if you intend to call the function only once, using setInterval is not ideal, as it creates a continuous loop. To avoid this, you can utilize clearInterval.

clearInterval: Canceling Timers

clearInterval allows you to stop a recurring timer. It accepts a handle returned by setInterval as an argument. By setting the handle to 0, you can cancel the timer and prevent it from firing further:

var handle = setInterval(drawAll, 20);

// When you want to cancel it:
clearInterval(handle);
handle = 0;

Using setTimeout for One-Time Execution

If you need to schedule a function to execute only once, use setTimeout instead. It provides similar functionality but doesn't create a recurring loop. The following code calls the drawAll() function once after a 20-millisecond delay:

setTimeout(drawAll, 20);

Remember, setInterval is suitable for creating timers that repeatedly execute a function, while clearInterval is used to stop such timers. On the other hand, setTimeout is used to schedule a function to fire only once after a specified delay.

The above is the detailed content of How to Use `setInterval` and `clearInterval` for Controlled Function Execution?. 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