-3

If setTimeout is synchronous why its non blocking? On which thread does it execute if not main thread?

user5573523
  • 41
  • 2
  • 10
  • 3
    Does this answer your question? [Combination of async function + await + setTimeout](https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout) – Greedo Aug 18 '20 at 09:18
  • The reason it's like this is that setTimeout predates promises. – Liam Aug 18 '20 at 09:20
  • 1
    `setTimeout` is asynchronous - but it does not have a `Promise`-API. The basic functionality of asynchronous functions is not `Promises`, but `Callbacks` (meaning giving a function that gets called asynchronously`. That's the function you pass into `setTimeout()` as a first argument. – David Losert Aug 18 '20 at 09:21

3 Answers3

1

Why setTimeout function does not return a promise?

Primarily because it predates Promises being added to the JS language.

Is setTimeout synchronous or asynchronous?

It runs synchronously and queues a function to run later.

why does setTimeout does not return a promise but a number?

It returns a number for use with clearTimeout.

Can we use await on setTimeout?

You can only usefully await a promise.


You can wrap a call to setTimeout in a promise and resolve it from the callback function you pass to setTimeout.

await new Promise( resolve => setTimeout(() => {
    // do whatever you like after 1s
    // then:
    resolve();
}, 1000);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

setTimeout is synchronous in nature. Its callback get registered by event loop in timer phase which will be executed an asynchronous manner.

user5573523
  • 41
  • 2
  • 10
0

Timeout function is asynchronous that is why it is non blocking. It is executed on main thread. Timeout function are executed as follows:

The callbacks of timers in JavaScript(setTimeout, setInterval) are kept in the heap memory until they are expired. If there are any expired timers in the heap, the event loop takes the callbacks associated with them and starts executing them in the ascending order of their delay until the timers queue is empty.

user5573523
  • 41
  • 2
  • 10