ProfNimrod
ProfNimrod

Reputation: 4310

Can javascript's 'setInterval' be configured to trigger immediately, and with an interval?

If I want to trigger an event regularly I use something like (coffeescript):

setInterval (() => myFunction()), 300000

But often I want myFunction called immediately, AND regular intervals thereafter. At present I do this by calling both setTimeout and setInterval, e.g.,

setTimeout (() => myFunction()), 0
setInterval (() => myFunction()), 300000

or

myFunction()
setInterval (() => myFunction()), 300000

Can setInterval be used to do this in one step?

Upvotes: 1

Views: 210

Answers (2)

techfoobar
techfoobar

Reputation: 66693

You can create a custom version of setInterval() that calls the specified function once at the start and then at intervals.

// custom version
window.setIntervalCustom = function(_callback, _delay) {
    _callback(); // call once
    return window.setInterval(_callback, _delay); // at intervals
};

// this will print 1 once at the start and then at intervals of 1000ms
setIntervalCustom(function() { console.log('1'); }, 1000);

Note: The custom function has been renamed above to avoid any conflict issues with other libs/code thiat might be using the original setInterval()

Upvotes: 1

cookie monster
cookie monster

Reputation: 10982

If your function is able to return itself, then yes.

function myFunction() {
    // do some work

    return myFunction;
}

setInterval(myFunction(), 300000);

I'll let you translate to CS.

So now you're invoking the function instead of passing it to setInterval(). The function runs, and returns itself, which is received by setInterval() and invoked as you'd expect.


I don't know CS, but it looks like you may be passing an anonymous function that invokes your function.

If so, I'm not sure why you're doing that, but it does guarantee that you can take this approach since you don't need to care about the return value of the original.

function myFunction() {
    // do some work
}

setInterval(function() {
    myFunction();

    return myFunction;
}(), 300000);

If there's more work to do in the anonymous function that should run at every interval, then give the function a name and change return myFunction; to return callback;.

function myFunction() {
    // do some work
}

setInterval(function callback() {
    myFunction();

    // some other work

    return callback;
}(), 300000);

Upvotes: 2

Related Questions