[javascript] Execute the setInterval function without delay the first time

It's there a way to configure the setInterval method of javascript to execute the method immediately and then executes with the timer

This question is related to javascript setinterval

The answer is


There's a problem with immediate asynchronous call of your function, because standard setTimeout/setInterval has a minimal timeout about several milliseconds even if you directly set it to 0. It caused by a browser specific work.

An example of code with a REAL zero delay wich works in Chrome, Safari, Opera

function setZeroTimeout(callback) {
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage('');
}

You can find more information here

And after the first manual call you can create an interval with your function.


To solve this problem , I run the function a first time after the page has loaded.

function foo(){ ... }

window.onload = function() {
   foo();
};

window.setInterval(function()
{
    foo(); 
}, 5000);

For someone needs to bring the outer this inside as if it's an arrow function.

(function f() {
    this.emit("...");
    setTimeout(f.bind(this), 1000);
}).bind(this)();

If the above producing garbage bothers you, you can make a closure instead.

(that => {
    (function f() {
        that.emit("...");
        setTimeout(f, 1000);
    })();
})(this);

Or maybe consider using the @autobind decorator depending on your code.


I'm not sure if I'm understanding you correctly, but you could easily do something like this:

setInterval(function hello() {
  console.log('world');
  return hello;
}(), 5000);

There's obviously any number of ways of doing this, but that's the most concise way I can think of.


There's a convenient npm package called firstInterval (full disclosure, it's mine).

Many of the examples here don't include parameter handling, and changing default behaviors of setInterval in any large project is evil. From the docs:

This pattern

setInterval(callback, 1000, p1, p2);
callback(p1, p2);

is identical to

firstInterval(callback, 1000, p1, p2);

If you're old school in the browser and don't want the dependency, it's an easy cut-and-paste from the code.


I stumbled upon this question due to the same problem but none of the answers helps if you need to behave exactly like setInterval() but with the only difference that the function is called immediately at the beginning.

Here is my solution to this problem:

function setIntervalImmediately(func, interval) {
  func();
  return setInterval(func, interval);
}

The advantage of this solution:

  • existing code using setInterval can easily be adapted by substitution
  • works in strict mode
  • it works with existing named functions and closures
  • you can still use the return value and pass it to clearInterval() later

Example:

// create 1 second interval with immediate execution
var myInterval = setIntervalImmediately( _ => {
        console.log('hello');
    }, 1000);

// clear interval after 4.5 seconds
setTimeout( _ => {
        clearInterval(myInterval);
    }, 4500);

To be cheeky, if you really need to use setInterval then you could also replace the original setInterval. Hence, no change of code required when adding this before your existing code:

var setIntervalOrig = setInterval;

setInterval = function(func, interval) {
    func();
    return setIntervalOrig(func, interval);
}

Still, all advantages as listed above apply here but no substitution is necessary.


Here's a wrapper to pretty-fy it if you need it:

(function() {
    var originalSetInterval = window.setInterval;

    window.setInterval = function(fn, delay, runImmediately) {
        if(runImmediately) fn();
        return originalSetInterval(fn, delay);
    };
})();

Set the third argument of setInterval to true and it'll run for the first time immediately after calling setInterval:

setInterval(function() { console.log("hello world"); }, 5000, true);

Or omit the third argument and it will retain its original behaviour:

setInterval(function() { console.log("hello world"); }, 5000);

Some browsers support additional arguments for setInterval which this wrapper doesn't take into account; I think these are rarely used, but keep that in mind if you do need them.


Here's a simple version for novices without all the messing around. It just declares the function, calls it, then starts the interval. That's it.

_x000D_
_x000D_
//Declare your function here_x000D_
function My_Function(){_x000D_
  console.log("foo");_x000D_
}    _x000D_
_x000D_
//Call the function first_x000D_
My_Function();_x000D_
_x000D_
//Set the interval_x000D_
var interval = window.setInterval( My_Function, 500 );
_x000D_
_x000D_
_x000D_


actually the quickest is to do

interval = setInterval(myFunction(),45000)

this will call myfunction, and then will do it agaian every 45 seconds which is different than doing

interval = setInterval(myfunction, 45000)

which won't call it, but schedule it only


_x000D_
_x000D_
// YCombinator_x000D_
function anonymous(fnc) {_x000D_
  return function() {_x000D_
    fnc.apply(fnc, arguments);_x000D_
    return fnc;_x000D_
  }_x000D_
}_x000D_
_x000D_
// Invoking the first time:_x000D_
setInterval(anonymous(function() {_x000D_
  console.log("bar");_x000D_
})(), 4000);_x000D_
_x000D_
// Not invoking the first time:_x000D_
setInterval(anonymous(function() {_x000D_
  console.log("foo");_x000D_
}), 4000);_x000D_
// Or simple:_x000D_
setInterval(function() {_x000D_
  console.log("baz");_x000D_
}, 4000);
_x000D_
_x000D_
_x000D_

Ok this is so complex, so, let me put it more simple:

_x000D_
_x000D_
function hello(status ) {    _x000D_
  console.log('world', ++status.count);_x000D_
  _x000D_
  return status;_x000D_
}_x000D_
_x000D_
setInterval(hello, 5 * 1000, hello({ count: 0 }));
_x000D_
_x000D_
_x000D_


You could wrap setInterval() in a function that provides that behavior:

function instantGratification( fn, delay ) {
    fn();
    setInterval( fn, delay );
}

...then use it like this:

instantGratification( function() {
    console.log( 'invoked' );
}, 3000);

You can set a very small initial delay-time (e.g. 100) and set it to your desired delay-time within the function:

_x000D_
_x000D_
var delay = 100;_x000D_
_x000D_
function foo() {_x000D_
  console.log("Change initial delay-time to what you want.");_x000D_
  delay = 12000;_x000D_
  setTimeout(foo, delay);_x000D_
}
_x000D_
_x000D_
_x000D_


I will suggest calling the functions in the following sequence

var _timer = setInterval(foo, delay, params);
foo(params)

You can also pass the _timer to the foo, if you want to clearInterval(_timer) on a certain condition

var _timer = setInterval(function() { foo(_timer, params) }, delay);
foo(_timer, params);