Wrap a timer in a promise, then chain .then calls so each step starts when the previous one finishes.
JavaScript · beginner · 8 min · 18 steps · free
function wait(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}
console.log('ordering coffee');
wait(300, 'coffee')
.then((drink) => {
console.log('got', drink);
return wait(200, 'cake');
})
.then((food) => console.log('got', food));
console.log('waiting…');wait already exists. This is called hoisting.ordering coffee.wait(300, "coffee") starts a 300 ms wait and returns a promise for the result.resolve: calling it later fulfils the promise.setTimeout hands the callback to a timer and returns at once. It will run after 300 ms, once the call stack is empty: see Timers waiting..then registers a callback and returns at once. JavaScript does not wait here: the callback runs later, when the promise settles.setTimeout callback gets no arguments and returns undefined.got coffee.wait(), with ms = 200 and value = "cake". It gets its own variables.(resolve) => { setTimeout(() …, with resolve = a built-in function. It gets its own variables.setTimeout hands the callback to a timer and returns at once. It will run after 200 ms, once the call stack is empty: see Timers waiting.wait returns Promise { <pending> }.setTimeout callback gets no arguments and returns undefined.Answer: Immediately
Answer: A new promise
← The Event Loop · async and await →