Stopping setTimeout Loops
When creating a loading indicator using a sprite, it's common to rely on a loop to cycle through background positions. One approach involves using the setTimeout function, but what if you need to stop the loop when the loading process completes?
setTimeout Implementation
The setTimeout function in JavaScript returns a timer handle that allows you to cancel the timeout using the clearTimeout function. To implement this, you can create a stop() function within the setBgPosition function:
function setBgPosition() { var c = 0, timer = 0; ... return stop; function stop() { if (timer) { clearTimeout(timer); timer = 0; } } }
To use this, you can assign the setBgPosition function to a variable and call the stop() function later to halt the loop:
var stop = setBgPosition(); // ... later ... stop();
Alternative Approach: setInterval
An alternative to using setTimeout is setInterval, which repeatedly executes a function at a specified interval. Here's how you can use it with clearInterval:
function setBgPosition() { ... return setInterval(run, 200); }
To stop the loop:
var timer = setBgPosition(); // ... later ... clearInterval(timer);
However, it's recommended to explore options for detecting the completion condition and allowing setBgPosition to stop the loop itself. This approach provides greater control and flexibility in handling loading operations.
The above is the detailed content of How to Stop a setTimeout or setInterval Loop for Loading Indicators?. For more information, please follow other related articles on the PHP Chinese website!