You are attempting to create a loading indicator using a sprite image and have encountered an issue stopping the loop once the load is complete. The function you have provided initiates a setTimeout loop that iterates through an array of values at specified intervals. The challenge lies in halting this loop programmatically.
To resolve this issue, you can utilize the timer handle returned by setTimeout. You can subsequently use clearTimeout to halt the timeout operation.
Here's a modified version of your code that incorporates this technique:
function setBgPosition() { var c = 0, timer = 0; var numbers = [0, -120, -240, -360, -480, -600, -720]; function run() { Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px'); if (c >= numbers.length) { c = 0; } timer = setTimeout(run, 200); } timer = setTimeout(run, 200); return stop; function stop() { if (timer) { clearTimeout(timer); timer = 0; } } } var stop = setBgPosition(); // ...later, when you're ready to stop... stop();
By assigning the timer handle to the timer variable, you can reference and clear it using clearTimeout when the load is finished.
Additionally, it's worth considering using setInterval instead of setTimeout in scenarios where repetitive execution is desired. This can simplify the code and provide a more robust solution.
Remember to implement proper mechanisms within setBgPosition itself to detect when the loop should terminate to ensure a self-contained and autonomous function.
The above is the detailed content of How to Stop a `setTimeout` Loop in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!