0

While studying Async and Performance from "You Don't Know JS" I tried this small code snippet:

var t = [];
var c = 1;

function foo() {
  t.push((performance.now()).toString());
  if (c < 50) {
    setTimeout(foo, 0);
    c++;
  }
}

For the first few times the browser (I used chrome) took less than 4ms to call foo. Later on it took somewhat little more than 4ms.

enter image description here.

I wanted to ask, despite being setTimeout() while creating a task why is it behaving like microtask for the first 3-4 times?

Kindly help me out, Thank You.

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33
  • What do you mean by "microtask" ? In fact, I don't quite get your question in general. You're simply running an async function and it will be executed in the next event cycle. – kemicofa ghost Oct 09 '19 at 17:33
  • the little time differences can have multiple reasons, since JS is executed in the browser, all operations done by the browser it self, background calls, caching etc. can influence the results. – Tobias Schäfer Oct 09 '19 at 17:35
  • in javascript microtasks are the tasks which are executed in less than 4ms rather than taken to next event cycle. for e.g. promise.then() is microtask. – Jyoti Mishra Oct 09 '19 at 17:42
  • Microtasks are a concept, they aren't tied to a specific length of time to execute (i.e. just because it's under 4ms doesn't make it a microtask). Specifically, microtasks are anything that falls into the job queue instead of the regular call stack: https://flaviocopes.com/javascript-event-loop/#es6-job-queue – Joseph Cho Oct 09 '19 at 17:52
  • If you're using `setTimeout(fn, 0)` to avoid stack-overflows, see [this Q&A](https://stackoverflow.com/a/43596323/633183). – Mulan Oct 10 '19 at 13:57

1 Answers1

1

To answer the question, the setTimeout() is an example of using the message queue. Microtasks are anything happen after each function is run, and before the message queue kicks in. The microtask queue is really the es6 job queue, but ever since v8 its been given a new name.

Just because the tasks take under 4ms doesn't make it a microtask. I have an example where the second sample took 5ms:

enter image description here

The reason for the interesting trend you found is most likely a Chrome optimization. The first few calls are done almost instantly, and as the call stack grows longer it digs deeper to grab more RAM.

if (c < 50) {
  setTimeout(foo, 10);
  c++;
}

If you try the above snippet you'll notice the timestamps are far more consistent. This is because the call stack is being added to at a more regular interval.

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33