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)
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With