I sort of understand what each is doing. setTimeout, "The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds." Async await, returns a promise, and is just a function that can be put in a queue and have the results of the function checked in later.
But both allow me to "delay code", they are both asynchronous functions. So when would you use one rather than the other one?
Thank you for any help!
I sort of understand what each is doing. setTimeout, "The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds." Async await, returns a promise, and is just a function that can be put in a queue and have the results of the function checked in later.
But both allow me to "delay code", they are both asynchronous functions. So when would you use one rather than the other one?
Thank you for any help!
Share Improve this question asked Jun 8, 2021 at 3:46 IkuraIkura 2482 silver badges18 bronze badges 2- 1 await usually wait for a code to complete. settimeout wait for a time instance to complete. – Sagar V Commented Jun 8, 2021 at 3:50
- 1 no, they don't. The first allows you to schedule code execution at some later time. The other lets you pause an async code path (and only and async code path) until a Promise has been resolved. – Mike 'Pomax' Kamermans Commented Jun 8, 2021 at 3:50
5 Answers
Reset to default 6They are completely different.
Using async
/await
allows you to consume Promises in a flat manner in your code, without nesting callbacks or hard-to-read .then
chains. For example:
const doSomething = async () => {
await asyncStep1();
await asyncStep2();
await asyncStep3();
};
where each async step returns a Promise.
await
only allows you to "delay" code in a block if you already have a Promise to work with (or something that you convert to a Promise).
setTimeout
is not similar at all to async
/await
- setTimeout
doesn't consume a Promise or have anything to do with Promises at all. setTimeout
allows you to queue a callback to be called later, after the timeout time has finished.
Unlike await
, setTimeout
does not delay code in a block - rather, you pass it a callback, and the callback gets called later.
Cool question.
You're right that they're both asynchronous code.
As a simple answer to the difference. If you are doing something like:
const fetchUser = async () => {
const result = await fetch("/user");
return await result.json();
}
async main1() {
setTimeout(() => console.log("done", 2000));
}
async main2() {
await fetchUser();
console.log("done");
}
The setTimeout is always going to take ~2000ms before it logs "done", provided you haven't blocked the thread somewhere else. The fetchUser
is going to log "done" when the API is complete, that might be 100ms, that might be 10000ms.
But the difference is a bit more involved than that:
It's partly to do with the difference in a callback style of code or a promise style of code.
The callback style is an older of coding, the difference here is a bit more than that.
Let's set aside setTimeout for a moment and talk about two ways you might make a fetch call.
const fetchUserOne = async() => {
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const json = await result.json();
return json;
}
const fetchUserTwo = () => {
return fetch('https://jsonplaceholder.typicode.com/todos/2')
.then(response => response.json())
};
async function main() {
const result1 = fetchUserOne();
const result2 = fetchUserTwo();
console.log(result1);
console.log(result2)
const awaitedResult1 = await result1;
const awaitedResult2 = await result2;
console.log(awaitedResult1);
console.log(awaitedResult2);
}
main().then(console.log("complete"));
Now what I want to highlight here, is that although the second example uses a callback style - they are both using promises.
When you run the code (and press F12 to see the full object), you'll note that the log of result1
and result2
are promises.
Window.setTimeout
on the other hand does not use a Promise.
const result = setTimeout(() => {
console.log("done");
}, 2000);
console.log(result);
The return value of the setTimeout
is a number, which can be used to cancel the timeout.
And that brings us to the main difference:
Promises are not cancellable, setTimeout is
See this Stack Overflow question about cancelling a promise.
To show an example of this, let's modify our example above.
const fetchUser = async () => {
const result = await fetch("https://jsonplaceholder.typicode.com/todos/1");
return await result.json();
}
let timeout;
async function main1() {
console.log("start main1");
timeout = setTimeout(() => console.log("done timeout"), 2000);
}
async function main2() {
console.log("start main2");
await fetchUser();
console.log("done fetchuser");
}
main1();
main2();
clearTimeout(timeout);
Above, we can see that we can quite easily abort the timeout call, whereas we can't cancel a promise directly.
This is not to say that you can't cancel that fetch request, as you can see in this thread, but you can't cancel the promise itself.
Firstly, setTimeout
is static timer that depends on the given time. On the other hand async await
is something that is not static. It will wait until it awaited function or promise return any response
or error
Secondly, You can Timeout
any execution but you cannot await any function.
Here is the Official doc Async await
setTimeout
allows you to delay execution for an approximate amount of time.
let log = () => console.log('log');
// invokes `log()` after a delay
setTimeout(log, 1000);
async/await
helps you deal with promises without function handlers; it's just syntactic sugar. It doesn't actually delay execution.
let promise = Promise.resolve(5);
let main = async() => {
// without await
promise.then(value => console.log(value));
// with await
console.log(await promise);
};
main();
Both async await and setTimeout aren't similar eventhough it looks like they are but they aren't. If you are new to JavaScript then, you can think of setTimeout as a timer, so whatever block of code or function is passed to setTimeout it will execute after a fixed time, it basically delays the execution of code, while on the other hand async await isn't bound to any timer, to understand simply, function or promise that uses async await will wait until the function or promise returns an appropriate response...