ArticleZip > Settimeout Is Not Waiting Duplicate

Settimeout Is Not Waiting Duplicate

Have you ever encountered the issue where your setTimeout function seems to run multiple times instead of waiting as expected? Don't worry, you're not alone. This common mistake can be easily resolved once you understand what's causing it.

The setTimeout function in JavaScript is used to execute a function after a specified amount of time. However, one common misconception is that it waits for the previous execution to complete before running again. This is not the case. If you call setTimeout multiple times, each call creates a new timer, regardless of whether previous timers have completed.

To prevent multiple executions, you can use a check to ensure that the timer is not already running before setting a new one. One way to achieve this is by creating a variable to store the timer ID and clearing the timer before setting a new one. This way, you can avoid stacking multiple timers on top of each other.

Javascript

let timerId;

function myFunction() {
    if (timerId) {
        clearTimeout(timerId);
    }
    
    timerId = setTimeout(() => {
        // Your code here
        console.log('Timer completed');
    }, 1000);
}

In this example, the `timerId` variable stores the ID of the timer. Before setting a new timer, it checks if there is an existing timer running and clears it using `clearTimeout`. This ensures that only one timer is active at a time.

Another approach is to use a flag variable to track whether the function is currently running. By setting the flag when the function starts and clearing it when it finishes, you can prevent multiple executions.

Javascript

let isRunning = false;

function myFunction() {
    if (isRunning) {
        return;
    }

    isRunning = true;

    setTimeout(() => {
        // Your code here
        console.log('Timer completed');
        isRunning = false;
    }, 1000);
}

In this example, the `isRunning` flag prevents the function from running if it is already in progress. Once the function completes, the flag is reset to `false`, allowing it to run again.

By implementing these simple checks, you can ensure that your setTimeout function behaves as expected and avoids unintentional duplicate executions. Remember to keep track of the timer state and handle it accordingly to prevent unexpected behavior in your code.

×