en.javascript.info/1-js/8-more-functions/07-settimeout-setinterval/3-rewrite-settimeout/task.md
Ilya Kantor f99574f53b up
2016-11-14 16:31:21 +03:00

448 B

importance: 4


Rewrite setTimeout with setInterval

Here's the function that uses nested setTimeout to split a job into pieces.

Rewrite it to setInterval:

let i = 0;

let start = Date.now();

function count() {

  if (i == 1000000000) {
    alert("Done in " + (Date.now() - start) + 'ms');
  } else {
    setTimeout(count, 0);
  }

  // a piece of heavy job
  for(let j = 0; j < 1000000; j++) {
    i++;
  }

}

count();