Skip to content

Instantly share code, notes, and snippets.

@AndersDJohnson
Last active December 6, 2024 14:35
Show Gist options
  • Save AndersDJohnson/4385908 to your computer and use it in GitHub Desktop.
Save AndersDJohnson/4385908 to your computer and use it in GitHub Desktop.
A synchronous version of setInterval (functional form). Waits for the interval function to finish before starting the timeout to the next call.
var setIntervalSynchronous = function (func, delay) {
var intervalFunction, timeoutId, clear;
// Call to clear the interval.
clear = function () {
clearTimeout(timeoutId);
};
intervalFunction = function () {
func();
timeoutId = setTimeout(intervalFunction, delay);
}
// Delay start.
timeoutId = setTimeout(intervalFunction, delay);
// You should capture the returned function for clearing.
return clear;
};
@ItzArty
Copy link

ItzArty commented May 12, 2022

Lovely, thanks!

@karthikironman
Copy link

Thanks, Dude!!!, it saved my time..........God bless..........

@siddacool
Copy link

How to clear interval

@AndersDJohnson
Copy link
Author

@siddacool this returns a function you can call to clear:

var clear = setIntervalSynchronous(fn, 1000):

// Later...

clear();

@oddmario
Copy link

oddmario commented Dec 5, 2024

Thank you so much for this! really needed it

I modified the function slightly to:

  • Allow calling the clear() function from inside the callback function
  • Catch any errors that may be thrown inside func
  • Await func if it's an async function. Without the await statement, the next setTimeout will be set without waiting for the first function execution to finish first.

Below is my modified version:

function setIntervalSynchronous(func, delay) {
    var timeoutId;
    var isStopped = false;

    var clear = function() {
        isStopped = true;
        clearTimeout(timeoutId);
    };

    var intervalFunction = async function() {
        if (isStopped) return;
        try {
            await func(); // Wait for the function to complete
        } catch (err) {
            console.error("Error in setIntervalSynchronous function:", err);
        }
        if (!isStopped) {
            timeoutId = setTimeout(intervalFunction, delay);
        }
    };

    timeoutId = setTimeout(intervalFunction, delay);
    return clear;
}

Now doing

var clear = setIntervalSynchronous(async function() {
    console.log("Hello World!");

    clear();
}, 1000);

should be possible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment