Home >Web Front-end >JS Tutorial >How Can I Ensure a Function Called with `setInterval` Executes Only Once?
Managing Scheduled Functions with setInterval and clearInterval
Consider the following code fragment:
function doKeyDown(event) { switch (event.keyCode) { case 32: /* Space bar was pressed */ if (x == 4) { setInterval(drawAll, 20); } else { setInterval(drawAll, 20); x += dx; } break; } }
The goal is to call the drawAll function only once, not create a loop that repeatedly invokes it.
Using clearInterval to Stop Recurring Execution
setInterval establishes a recurring timer that calls the specified function periodically. To cease its execution, we can utilize clearInterval. Here's how it works:
var handle = setInterval(drawAll, 20); // When you want to stop it: clearInterval(handle); handle = 0; // Indication of an uncleared interval
On browsers, the handle is guaranteed to be a non-zero numerical value. Thus, setting handle = 0 serves as a convenient flag to indicate that the interval has been cleared.
Scheduling a One-time Function Call
If the intention is to execute a function only once, consider using setTimeout instead. This function schedules a function to be invoked after a specified time interval but doesn't continue firing it thereafter. It also returns a handle for potential cancellation.
setTimeout(drawAll, 20);
The above is the detailed content of How Can I Ensure a Function Called with `setInterval` Executes Only Once?. For more information, please follow other related articles on the PHP Chinese website!