It's there a way to configure the setInterval
method of javascript to execute the method immediately and then executes with the timer
-
8Not natively though. You can try calling the `function` once and then doing the `setInterval()` – Mrchief Jul 13 '11 at 20:46
18 Answers
It's simplest to just call the function yourself directly the first time:
foo();
setInterval(foo, delay);
However there are good reasons to avoid setInterval
- in particular in some circumstances a whole load of setInterval
events can arrive immediately after each other without any delay. Another reason is that if you want to stop the loop you have to explicitly call clearInterval
which means you have to remember the handle returned from the original setInterval
call.
So an alternative method is to have foo
trigger itself for subsequent calls using setTimeout
instead:
function foo() {
// do stuff
// ...
// and schedule a repeat
setTimeout(foo, delay);
}
// start the cycle
foo();
This guarantees that there is at least an interval of delay
between calls. It also makes it easier to cancel the loop if required - you just don't call setTimeout
when your loop termination condition is reached.
Better yet, you can wrap that all up in an immediately invoked function expression which creates the function, which then calls itself again as above, and automatically starts the loop:
(function foo() {
...
setTimeout(foo, delay);
})();
which defines the function and starts the cycle all in one go.

- 334,560
- 70
- 407
- 495
-
8
-
40@Sangdol because it ensures that timer events don't "stack" if they're left unprocessed. In some circumstances a whole load of `setInterval` events can arrive immediately after each other without any delay. – Alnitak May 29 '12 at 10:05
-
2I like the last block of code you posted. And good point with setTimeout(); you guarantee the previous cycle is complete before the second one is even scheduled. – styfle Aug 16 '12 at 21:51
-
11
-
4@GauravBhor, the same way you would stop the setInterval, remembering the id returned by setTimeout and then calling clearTimeout(id)... Or setting a condition to run or not the next interval in your function. – rvignacio Jul 14 '14 at 13:21
-
Since you're calling recursively without any exit condition doesn't this keep eating up memory indefinitely? – Dave Munger Nov 16 '15 at 05:18
-
8@DaveMunger no, because it's not truly recursive - it's only "pseudo-recursive". The "recursive" calls don't happen until the browser returns to the event loop, at which point the call stack has been completely unwound. – Alnitak Nov 16 '15 at 07:57
-
Delay here is not the exact time interval between two `foo` call, it is delay + running time of `...` part. Use `setInterval` to be more exact if needed – yılmaz Jan 15 '16 at 12:30
-
You could use a variable timeout based on the start time using Date.now() if getting the right (milli)second matters. – Chinoto Vokro May 24 '16 at 19:54
-
I was using setInterval...but the "stacking" @Alnitak mentioned was in effect in my case. This type of concurrency issue made it tricky to figure out what was going on. Used option 2. Works perfectly, thanks. – Timothy Lee Russell Aug 09 '16 at 04:16
-
@yılmaz it would be trivial to measure the time delay between entering the function and subsequently calling `setTimeout` and adjusting the iteration delay accordingly. I've actually done exactly that in the past to create a clock that ticks more accurately than one that just uses `setTimeout(tick, 1000)` – Alnitak Aug 09 '16 at 08:03
-
1Potential issues with this solution: If you want to stop the timer after it's already fired you won't be able to. I.e. the timeout schedules a call for 5000ms and in 1000ms you decide you want to cancel the loop. The result is an action occurring 4000ms after you told it to stop. You won't be able to stop it without having an identifier for that timeout - which means it might as well be an interval. There are ways around this, but at that point you're reinventing setInterval. Unless you're making an atomic clock, just call the function before you set the iteration. – Polyducks Jul 31 '18 at 08:16
-
1@Polyducks that would be easy enough to resolve with e.g. `if (!cancelled) { ... }` in the start of the callback. `setInterval` has its own problems with event stacking (as I already described). – Alnitak Jul 31 '18 at 08:52
-
1It's better to use the first approach, since setInterval returns an identifier to clear the interval. For example: `var interval = setItmeout(...); ... clearInterval(interval)`. – Cequiel Feb 08 '20 at 16:09
-
1Please, keep in mind that with `setInterval()`, calling a whole stack of events in one go is sometimes desired. – Danon Nov 18 '20 at 12:09
-
Remember to put a semi before the IIFE if you're having troubles if you don't normally use semicolons. – Rodrigo García Nov 30 '20 at 21:00
-
I recommend using await Promise instead of setTimeout within the self-calling func. Allows for finer granularity of control to exit out of any given loop. If you can't use async then setTimeout is a decent fallback, but with setTimeout once it's queued you can't unqueue it. With await Promise you can add a bail-out check between the promise's resolve() and the execution of the next iteration. – 1337ingDisorder Apr 16 '22 at 00:27
-
In your second and third examples, you should wrap the `...` part with `try...catch`, because if an error is thrown, the `setInterval` will never be called, and your interval-timed function will stop working. – Luke Hutchison Jul 28 '22 at 01:19
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.

- 14,322
- 3
- 32
- 24
-
25This is a cool answer because it's a named function that executes immediately and also returns itself. Exactly what I was looking for. – jamesmortensen Feb 17 '14 at 22:40
-
78Definitely a cool solution, but likely to cause confusion for people reading in the future. – Deepak Joy Cheenath Sep 03 '15 at 09:31
-
4You don't need to give it a name 'hello'. You could instead return arguments.callee and have the same with an anonymous function – JochenJung Sep 24 '15 at 14:32
-
12
-
12This is the kind of Javascript code that will confuse most new JS programmers who have come from other languages. Write a bunch of stuff like this if your company doesn't have a lot of JS personnel and you want job security. – Ian Jul 21 '17 at 18:26
-
4any code like this better have comments to indicate what it is intending to do, or else people modifying it or fixing bug could run into issues. Side note: of course nowadays I see people not putting comments in their code because as much as companies want to make programmers dispensable, (some) programmers want to make themselves as indispensable as possible, or to gain power in the company. But then this programmer may leave, and with a lot of code by different programmers without comments like this, the whole code base will turn into a mess – nonopolarity Dec 15 '17 at 09:08
-
is there any way to write this in es6? like `() => { ... what to return? }` – Rafath Jul 28 '20 at 22:17
-
4Don't use this. It's hard to see that it is called before pass it as argument. As JS developer I love it (and I didn't know it) , but I love clean code more. – Howarto Dec 05 '20 at 15:13
-
If you are wondering why this works: 1. Search "Immediately Invoked Function Expression" or IIFE; 2. The return passes an anonymous function object (i.e functions are first-class) to setInterval; since that object is being referenced, it's not garbage collected. – spot Dec 23 '21 at 20:49
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.

- 17,110
- 4
- 30
- 33
-
I prefer this solution over the `setTimeout` solution because it returns a `setInterval` object. To avoid calling functions which maybe are later in the code and therefore undefined at the current time, I wrap the first function call in a `setTimeout` function like this: `setTimeout(function(){ func();},0);` The first function is then called after the current processing cycle, which is also _immediately_, but is more error proven. – pensan Oct 02 '16 at 10:33
-
You could use a `...args` argument and use it as `...args` again in each function... – Ath.Bar. May 11 '21 at 18:35
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);

- 318,772
- 63
- 451
- 440
-
10I think you should return what setInterval returns. This is because otherwise you can't use clearInterval. – Henrik R Nov 30 '16 at 13:19
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.

- 16,261
- 16
- 62
- 78
-
11Overriding native browser functions is terrible since it can break other coexisting code when the specs change. In fact, setInterval currently has more parameters: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval – Áxel Costas Pena Jun 07 '16 at 12:49
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.
//Declare your function here
function My_Function(){
console.log("foo");
}
//Call the function first
My_Function();
//Set the interval
var interval = window.setInterval( My_Function, 500 );

- 213
- 2
- 13
-
2That's exactly what the accepted answer does in the first few line. How does this answer add anything new? – Dan Dascalescu Sep 23 '18 at 06:45
-
The accepted answer goes on to say not to do this. My response to the accepted answer explains why it's still a valid method. The OP specifically asks for calling setInterval's function on its first call but the accepted answer diverts to talk about the benefits of setTimeout. – Polyducks Oct 23 '18 at 09:12
-
The right answer for me with the interval OUTSIDE the function and underneath, otherwise I could not clear the Interval, the `var interval` is undefined. Actually I used a Timeout, as @Alnitak pointed out. – FFish Jan 20 '23 at 20:40
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.

- 948
- 1
- 14
- 36
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);

- 1,765
- 1
- 25
- 42
-
-
you set the timer from the second call, for the first time you just call the fn directly. – Jayant Varshney Jul 31 '18 at 13:11
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.

- 12,550
- 7
- 61
- 73
You can set a very small initial delay-time (e.g. 100) and set it to your desired delay-time within the function:
var delay = 100;
function foo() {
console.log("Change initial delay-time to what you want.");
delay = 12000;
setTimeout(foo, delay);
}

- 21
- 4
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);

- 5,149
- 12
- 28
- 32
If you can use RxJS, there is something called timer()
:
import { Subscription, timer } from 'rxjs';
const INITIAL_DELAY = 1;
const INTERVAL_DELAY = 10000;
const timerSubscription = timer(INITIAL_DELAY, INTERVAL_DELAY)
.subscribe(() => {
this.updateSomething();
});
// when destroying
timerSubscription.unsubscribe();

- 961
- 14
- 19
This example builds on @Alnitak's answer, but uses await Promise for finer granularity of control within the loop cycle.
Compare examples:
let stillGoing = true;
(function foo() {
console.log('The quick brown fox did its thing');
if (stillGoing) setTimeout(foo, 5000);
})();
foo();
In the above example we call foo() and then it calls itself every 5 seconds.
But if, at some point in the future, we set stillGoing to false in order to stop the loop, we'll still get an extra log line even after we've issued the stop order. This is because at any given time, before we set stillGoing to false the current iteration will have already created a timeout to call the next iteration.
If we instead use await Promise as the delay mechanism then we have an opportunity to stop the loop before calling the next iteration:
let stillGoing = true;
(async function foo() {
console.log('The quick brown fox did its thing');
await new Promise(resolve => setTimeout(resolve, 5000));
if (stillGoing) foo();
})();
foo();
In the second example we start by setting a 5000ms delay, after which we check the stillGoing value and decide whether calling another recursion is appropriate.
So if we set stillGoing to false at any point, there won't be that one extra log line printed after we set the value.
The caveat is this requires the function to be async, which may or may not be an option for a given use.

- 821
- 1
- 6
- 17
For Those using React, here is how I solve this problem:
const intervalRef = useRef(0);
useEffect(() => {
if (condition is true){
if (intervalRef.current === 0) {
callMyFunction();
}
const interval = setInterval(() => {
callMyFunction();
}, 5_000);
intervalRef.current = interval;
} else {
clearInterval(intervalRef.current);
}
}, [deps]);

- 2,140
- 4
- 32
- 51
// YCombinator
function anonymous(fnc) {
return function() {
fnc.apply(fnc, arguments);
return fnc;
}
}
// Invoking the first time:
setInterval(anonymous(function() {
console.log("bar");
})(), 4000);
// Not invoking the first time:
setInterval(anonymous(function() {
console.log("foo");
}), 4000);
// Or simple:
setInterval(function() {
console.log("baz");
}, 4000);
Ok this is so complex, so, let me put it more simple:
function hello(status ) {
console.log('world', ++status.count);
return status;
}
setInterval(hello, 5 * 1000, hello({ count: 0 }));

- 428
- 4
- 4
With ES2017, it may be preferable to avoid setInterval
altogether.
The following solution has a much cleaner execution flow, prevents issues if the function takes longer than the desired time to complete, and allows for asynchronous operations.
const timeout = (delayMs) => new Promise((res, _rej) => setTimeout(res, delayMs));
const DELAY = 1_000;
(async () => {
while (true) {
let start_time = Date.now();
// insert code here...
let end_time = Date.now();
await timeout(DELAY - (end_time - start_time));
}
})();

- 5,601
- 7
- 63
- 105
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.

- 47
- 1
- 4
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

- 64
- 4
-
1
-
2This works only if `myFunction()` does return itself. Instead modifying each function to be called by `setInterval` it is a better approach to wrap `setInterval` once like the other answers are proposing. – Jens Wirth Apr 12 '16 at 11:43