Stopping a setTimeout Loop
In the provided code, a setTimeout loop is used to continuously set the background position of an image sprite, creating a loading animation. However, it's necessary to control when the loop is stopped once the loading is completed.
The solution involves using the timer handle returned by setTimeout. This handle can be used in conjunction with clearTimeout to stop the timeout.
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; } } }
This revised code defines a stop function within setBgPosition. The stop function checks if the timer handle is present and, if so, clears it with clearTimeout. The updated code can be used as follows:
var stop = setBgPosition(); // ...later, when you're ready to stop... stop();
Alternatively, setInterval can be used instead of setTimeout to create a repeating loop. However, setInterval requires clearInterval to stop the loop.
function setBgPosition() { var c = 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; } } return setInterval(run, 200); }
This code can be used as follows:
var timer = setBgPosition(); // ...later, when you're ready to stop... clearInterval(timer);
Finally, it's recommended to consider using a condition within setBgPosition itself to detect the completion of the loading process and automatically stop the loop.
The above is the detailed content of How to Stop a `setTimeout` or `setInterval` Loop in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!