Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does setTimeout() run on a separate thread?

Curious to see whether setTimeout() will be fired up asynchronously, I tried the following test script:

function timedText() {
  var x = document.getElementById("txt");
  setTimeout(function() {
    x.value = "1 second"
  }, 1000);
  setTimeout(function() {
    x.value = "2 seconds"
  }, 2000);
  setTimeout(function() {
    x.value = "3 seconds"
  }, 3000);

  while (true) {}
}
<p>Click on the button below. The input field will tell you when two, four, and six seconds have passed.</p>

<button onclick="timedText()">Display timed text</button>
<input type="text" id="txt">

Sure enough, clicking the button causes the browser to hang.

This tells me that setTimeout() does not run on a separate thread.

But on a recent interview, the interviewer suggested otherwise... Does that mean that setTimeout() is browser/implementation dependent?

like image 796
Very Objective Avatar asked Aug 22 '18 06:08

Very Objective


3 Answers

JavaScript is not multi threaded. Well there are WebWorkers that run in a different thread, but that's not really multi threading, more like multiple processes, that communicate with each other.

As of that the while (true) {} will block the js context, because it is an endless loop.

The setTimeout will register a function for later execution. But at no time code will run in parallel for the same context.

A while (true) itself does not necessarily create a blocking loop:

async function sleep(time) {
  return new Promise((resolve, _) => setTimeout(resolve, time))
}

async function test(val) {
  while (true) {
    console.log('in while loop ' + val)
    await sleep(1000)
  }
}

test('foo')
test('bar')

So you can say with await/async you can create some kind of cooperative multitasking like setup, but still no multi threading

like image 197
t.niese Avatar answered Sep 18 '22 11:09

t.niese


There is no thread in javascript. setTimeout push just the delegate function insto a stack that will pop for the next pass. You can read that JavaScript and Threads

like image 25
Silvinus Avatar answered Sep 18 '22 11:09

Silvinus


This tells me that setTimeout() does not run on a separate thread.

Yes. There is only one thread in JS.

But on a recent interview, the interviewer suggested otherwise... Does that mean that setTimeout() is browser/implementation dependent?

As far as i know only engine changed from browser to browser. Internal mechanism stands the same - event-loop processor.

like image 32
Dmitry Surin Avatar answered Sep 18 '22 11:09

Dmitry Surin