1

Both setTimeout and web worker more or less do the same thing. They make the main thread non-blocking and does it's work asynchronously in the background. How do we judge when to use what?

Ayan Dalal
  • 69
  • 1
  • 3
  • 1
    IMHO they are nowhere close to doing the same thing. `setTimeout()` delays the execution of a code block. `WebWorker` allow to move extensive calculations to a separate thread. – Sirko Jun 07 '18 at 08:59

1 Answers1

5

They make the main thread non-blocking and does it's work asynchronously in the background.

No. They don't. That's what a Web Worker does.

setTimeout puts a function on a queue to be run later. When it runs it still runs on the main thread and is just as blocking.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Okay I get it. But both serve the same purpose right? I can achieve the same goal which I can, through web worker. So, is web worker recommended because it is time independent? And also, why ajax calls don't use web workers instead of setTimeout? – Ayan Dalal Jun 07 '18 at 09:10
  • "why ajax calls don't use web workers instead of setTimeout?" — They typically don't use either! – Quentin Jun 07 '18 at 09:16
  • "So, is web worker recommended because it is time independent?" — No. Because it does work outside the main thread so it is non-blocking. – Quentin Jun 07 '18 at 09:17
  • @AyanDalal depends on the implementation. AJAX as a concept, does not mention setTimeout. https://www.w3schools.com/xml/ajax_intro.asp – Vladimir M Jun 07 '18 at 09:18
  • "why ajax calls don't use web workers instead of setTimeout?" — They typically don't use either! - what exactly do they use then? – Ayan Dalal Jun 07 '18 at 09:20
  • XMLHttpRequest or fetch – Quentin Jun 07 '18 at 09:20
  • "XMLHttpRequest or fetch" - how do they listen to onreadystatechange? – Ayan Dalal Jun 07 '18 at 09:22
  • Their support for asynchronous operations is built-in (and not written in JS). – Quentin Jun 07 '18 at 09:24