Using setInterval and clearInterval Effectively
In JavaScript, setInterval allows you to set up a timer that fires repeatedly at a specified interval. This can be useful for animation or other tasks that require a loop. However, in some cases, you may only want to execute a function once, rather than continuously.
Using clearInterval to Interrupt a Scheduled Loop
If you have set up a timer using setInterval, you can use clearInterval to stop it from firing. This is useful if you want to terminate the loop prematurely:
var handle = setInterval(drawAll, 20); // When you want to cancel it: clearInterval(handle); handle = 0; // Flag to indicate cleared interval
The handle returned by setInterval is typically a number that isn't equal to 0. Therefore, using 0 as a flag value indicates that no timer is set.
Scheduling a One-Time Function Call with setTimeout
Instead of using setInterval for one-time function calls, consider using setTimeout instead:
setTimeout(drawAll, 20);
setTimeout schedules a function to fire once, at the specified time interval. It does not create a loop. You can also use clearTimeout to cancel the timer before it fires if necessary.
The above is the detailed content of How to Effectively Use `setInterval` and `clearInterval` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!