Home > Web Front-end > CSS Tutorial > How to Stop a `setTimeout` Loop in JavaScript?

How to Stop a `setTimeout` Loop in JavaScript?

Barbara Streisand
Release: 2024-12-01 09:26:15
Original
111 people have browsed it

How to Stop a `setTimeout` Loop in JavaScript?

How to Control the Execution of a setTimeout Loop

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template