Execute asynchronous javascript code every X seconds

2.9k Views Asked by At

How to execute asynchronous js code (written in node.js) every X seconds and ensure that the new execute/call won't be started before the callback (success, error) from asynchronous function is executed. Code example:

asyncFunc(function(successData){
  // do something with successData
}, function(errorData){
  // do something with errorData
});

setInterval comes to my mind firstly, but I think it won't ensure what I want, if the callback doesn't execute inside interval, it will go to the queue.

EDIT: To simplify case, repeat async function call 1 second after its callback finishes.

2

There are 2 best solutions below

0
On

You can use setTimeout like this:

(function loop() {
    asyncFunc(function(successData){
        setTimeout(loop, X);
    }, function(errorData){
        // If you still want to continue:
        setTimeout(loop, X);
    });
})(); // execute immediately

This will start the delay when the async call triggers the callback.

0
On

Consider abstracting the problem with a re-usable method that'll allow you to specify the function to call, the interval at which it's called, and the callbacks to invoke:

function repeatAsync(func, interval, success, error) {
    (function loop() {
        func(
            () => {
                success();
                setTimeout(loop, interval);
            },
            () => {
                error();
                setTimeout(loop, interval);
            }
        );
    })();   // invoke immediately
}

If you want the chain of calls to be broken on error, replace the second argument to func with just error, i.e. func( () => { ... }, error)