Is it possible to chain setTimout functions to ensure they run after one another?
Is it possible to chain setTimout functions to ensure they run after one another?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Three separate approaches listed here:
setTimeout()callbacks.setTimeout()in a promise and chain promises.Manually Nest setTimeout callbacks
Of course. When the first one fires, just set the next one.
Chainable Timer Object
You can also make yourself a little utility object that will let you literally chain things which would let you chain calls like this:
Wrap setTimeout in a Promise and Chain Promises
Or, since it’s now the age of promises in ES6+, here’s similar code using promises where we let the promise infrastructure do the queuing and sequencing for us. You can end up with a usage like this:
Here’s the code behind that:
The functions you supply to this version can either by synchonrous or asynchronous (returning a promise).