Home >Web Front-end >CSS Tutorial >How to Stop a setTimeout or setInterval Loop for Loading Indicators?

How to Stop a setTimeout or setInterval Loop for Loading Indicators?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 03:05:11991browse

How to Stop a setTimeout or setInterval Loop for Loading Indicators?

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!

Statement:
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