Execute the setInterval function without delay the first time
Asked Answered
L

18

552

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

Loats answered 13/7, 2011 at 20:44 Comment(1)
Not natively though. You can try calling the function once and then doing the setInterval()Halcomb
M
784

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.

Meri answered 13/7, 2011 at 20:45 Comment(18)
Why do you prefer setTimeout?Harms
@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.Meri
I 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.Coeliac
How do I stop the function if I use the setTimeout method?Micronucleus
@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.Boak
Since you're calling recursively without any exit condition doesn't this keep eating up memory indefinitely?Greenock
@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.Meri
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 neededKoala
You could use a variable timeout based on the start time using Date.now() if getting the right (milli)second matters.Stalinism
I was using setInterval...but the "stacking" @Meri 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.Mcatee
@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)Meri
Potential 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.Edana
@Edana 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).Meri
It's better to use the first approach, since setInterval returns an identifier to clear the interval. For example: var interval = setItmeout(...); ... clearInterval(interval).Verbal
Please, keep in mind that with setInterval(), calling a whole stack of events in one go is sometimes desired.Coco
Remember to put a semi before the IIFE if you're having troubles if you don't normally use semicolons.Embrey
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.Raddle
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.Nolte
D
291

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.

Donative answered 13/7, 2011 at 20:52 Comment(9)
This is a cool answer because it's a named function that executes immediately and also returns itself. Exactly what I was looking for.Quadrature
Definitely a cool solution, but likely to cause confusion for people reading in the future.Farlee
You don't need to give it a name 'hello'. You could instead return arguments.callee and have the same with an anonymous functionSubdelirium
@Subdelirium arguments.callee is not available in ES5 strict modeMeri
This 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.Nydia
any 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 messIcs
is there any way to write this in es6? like () => { ... what to return? }Loyal
Don'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.Mannie
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.Etesian
U
47

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.

Usable answered 13/4, 2016 at 8:40 Comment(2)
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.Housewifely
You could use a ...args argument and use it as ...args again in each function...Lasonyalasorella
T
11

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);
Travers answered 13/7, 2011 at 20:54 Comment(1)
I think you should return what setInterval returns. This is because otherwise you can't use clearInterval.Beeswing
L
7

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.

Lelandleler answered 9/4, 2013 at 21:27 Comment(1)
Overriding native browser functions is terrible since it can break other coexisting code when the specs change. In fact, setInterval currently has more parameters: developer.mozilla.org/en-US/docs/Web/API/WindowTimers/…Kalvn
E
5

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 );
Edana answered 31/7, 2018 at 8:24 Comment(3)
That's exactly what the accepted answer does in the first few line. How does this answer add anything new?Eldwon
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.Edana
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 @Meri pointed out.Lying
B
3

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.

Banc answered 6/4, 2018 at 17:20 Comment(0)
H
3

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);
}
Hallucinosis answered 12/6, 2020 at 4:56 Comment(0)
S
2

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);
Sephira answered 24/3, 2017 at 11:48 Comment(2)
Could you explain this in more depth?Edana
you set the timer from the second call, for the first time you just call the fn directly.Sephira
A
2

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.

Assiduity answered 10/1, 2019 at 1:55 Comment(0)
C
1

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);
Coacher answered 9/6, 2015 at 9:8 Comment(0)
P
1

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();
Prelude answered 6/4, 2022 at 14:22 Comment(0)
R
1

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.

Raddle answered 16/4, 2022 at 0:55 Comment(0)
P
1

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]);
Phoenix answered 21/10, 2022 at 11:18 Comment(0)
H
0

// 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 }));
Heteroclite answered 28/3, 2016 at 16:2 Comment(1)
This is vastly over engineered.Edana
S
0

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));
  }
})();
Sitting answered 6/2, 2023 at 14:57 Comment(0)
C
-2

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.

Coniah answered 2/3, 2013 at 4:16 Comment(0)
S
-10

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

Sylas answered 24/6, 2013 at 15:2 Comment(2)
Where did you get that from?Spirelet
This 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.Usable

© 2022 - 2024 — McMap. All rights reserved.