David Ramirez
David Ramirez

Reputation: 392

setTimeout executing now and given time

is there a way to have setTimeout run immediately then run again at the time given. for example i want this updateItemsCache function to run on load then run again every 3 seconds.

right now its only getting executed every 3 seconds.

function updateItemsCache(){
  setTimeout(() => {
  //do stuff
  }, 30000);

}

Upvotes: 2

Views: 102

Answers (3)

Alexander
Alexander

Reputation: 70

The following code will declare a function that contains a setTimeout that runs the function itself. Remember to put the call to the function as the last thing in your setTimeout.

Then all you have to do is to call yout timeoutFunction().

This will make sure that your code (that you put by "//do stuff") runs when you call the function. And, by calling the timeoutFunction, runs again after your desired delay (ms).

const timeoutFunction = () => {
    setTimeout(() => {
        //do stuff
        timeoutFunction();
    }, ms);
}
timeoutFunction();

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30360

If I understand your question correctly, you could structure your code as shown below to this.

In summary, you can call a function (ie doStuff()) on regular 3 second intervals via setTimeout(iteration, 3000); where iteration is a function that:

  • calls your custom application logic that you want executed on 3 second intervals and,
  • schedules the next iteration (ie to happen 3 seconds into the future)

This pattern also ensures that the logic is run both immediately, and on 3 second intervals beyond the first execution:

const doStuff = () => {
  console.log(`Do stuff at ${Date.now()}`);
}


function updateItemsCache(){
  
  /*
  Define iteration function that invokes your
  "stuff" logic
  */
  const iteration = () => {
    
    doStuff();
    
    /*
    Use setTimeout() to schedule the next iteration
    at 3 seconds into the future (which will cause the
    iteration to repeat on 3 second intervals)
    */
    setTimeout(iteration, 3000);
  }
  
  /*
  Start iteration which calls you "stuff" logic
  immediately, and reschedules another iteration
  */
  iteration();
}

updateItemsCache();
  

Upvotes: 0

Yftach
Yftach

Reputation: 752

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

No, just create a function and call it once before the timeout, and once inside the timeout

function updateItemsCache(){
  innerLogic()
  setTimeout(innerLogic, 30000);

}

function innerLogic(){

}

Upvotes: 2

Related Questions