Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we make set Interval to wait until its function inside it is executed?

I am trying to make an animation (Although I have not given exact code but an example of what I want to do) like I want that set Interval to wait until its inner function is completely executed then run itself again. There are many similar questions like how to make setInterval Wait until The function executes? (you are thinking of this question sounds similar to this question but this question's answer is not elaborating what's going on) and Wait until setInterval() is done but these questions are not giving my answer. Can anyone tell me is it possible to do this? (if possible) then how?

setInterval(()=>{
 setTimeout(()=>{
  console.log("hel1o")
 },3000)
},1000)
like image 587
Shayan Kanwal Avatar asked Sep 05 '25 03:09

Shayan Kanwal


1 Answers

You can use recursion and promises to do this. First wrap the code that you plan to execute in a function that returns a promise. Then create a recursive function that calls itself once the action is complete.

const action = () => new Promise((resolve, reject) => {
  console.log("Action init")
  return setTimeout(()=>{
    console.log("Action completed")
    resolve();
  },3000)
})

const actionRecursion = () => {
  action().then(() => {
    setTimeout(actionRecursion, 1000)
  })
}

actionRecursion();
like image 171
Akshay Avatar answered Sep 07 '25 21:09

Akshay