educative.io

In case of async await , how does the setTimeout (any web api ) work?

as await makes the function pause, then how does any web api resolves instantly as it first goes in callback queue and await until the call stack is empty. what i want to ask here is , how for eg setTimeout () gave us the result instant when called inside promises?
eg–> function wait(secondsToWait) {
return new Promise(resolve => {
setTimeout(
() => resolve(Resolved after ${secondsToWait} seconds),
secondsToWait * 1000
);
});
}

async function fn() {
console.log(‘Beginning fn’);

const result = await wait(2);
console.log(result);

console.log('Ending fn');

}

fn();

Hi @rishabh_jain
setTimeout () gave us instant results because we have set 2 seconds time for the wait which is very less that’s why it seems like an instant.
If we update the time for 2 to 25 seconds then it will not give the instant results, you can verify it by doing the following change in the code.
Screenshot 2022-09-05 at 4.07.21 PM

Hope it will help, Thank you :blush:

1 Like

Thanks for the explanation.
But this is not what I want . I think u did not understand my question properly or i was not properly described my question.
Ok, so as we all know settimeout is web api. So whenever js engine encounters any web api let’s says settimeout here , js engine will send it to callback queue and until the call stack becomes empty, all the things inside callback queue stays there only and when call stack becomes empty , functions on CB queue sends to call stack and execute.
So, my question here is when such thing happens in
JS engine, so why in wait function ( in the example i have initially ) js engine wait until
Promise resolve ( used settimeout () inside promise) and gave us the result and after that continue the
remaining execution.