Home >Web Front-end >JS Tutorial >How Can I Control Recurring Timers in JavaScript Using `setInterval` and `clearInterval`?
Controlling Recurring Timers with setInterval and clearInterval
In your code, you aimed to invoke drawAll() once when a specific key was pressed. However, the setInterval function establishes a recurring timer that repeatedly calls drawAll(). To address this, we can employ clearInterval to halt the execution of the timer loop.
setInterval creates a recurring timer and returns a handle. This handle serves as an identifier that can be used by clearInterval to stop the timer from triggering. Here's how it works:
var handle = setInterval(drawAll, 20); // When you want to cancel it: clearInterval(handle); handle = 0; // This marks the interval as cleared
On browsers, the handle is guaranteed to be a non-zero number. Therefore, using 0 as the handle value indicates that no timer is set.
To schedule a function to fire only once, you can use setTimeout instead of setInterval. setTimeout executes a function once after a specified delay. It returns a handle that can be used with clearTimeout to cancel the function call before it executes if necessary:
setTimeout(drawAll, 20);
The above is the detailed content of How Can I Control Recurring Timers in JavaScript Using `setInterval` and `clearInterval`?. For more information, please follow other related articles on the PHP Chinese website!