There are two runners:

var runner1 = new Runner(); var runner2 = new Runner(); 

Everyone has a step () method that takes a step by increasing the steps property.

The specific code of the step () method does not matter; it’s only important that the step is not done instantly, it takes a little time.

If you run the first runner through setInterval, and the second - through the nested setTimeout - which one will take more steps in 5 seconds?

 function Runner() { this.steps = 0; this.step = function() { this.doSomethingHeavy(); this.steps++; }; function fib(n) { return n <= 1 ? n : fib(n - 1) + fib(n - 2); } this.doSomethingHeavy = function() { for (var i = 0; i < 25; i++) { this[i] = fib(i); } }; } var runner1 = new Runner(); var runner2 = new Runner(); // запускаем бегунов var t1 = setInterval(function() { runner1.step(); }, 15); var t2 = setTimeout(function go() { runner2.step(); t2 = setTimeout(go, 15); }, 15); // кто сделает больше шагов? setTimeout(function() { clearInterval(t1); clearTimeout(t2); alert( runner1.steps ); alert( runner2.steps ); }, 5000); 

About the work of the setTimeout () methods of recursive and setInterval () in different browsers, I understand everything. One thing is not clear: in this code, when calling a recursive setTimeout (due to its specificity: a fixed pause between calls), the doSomethingHeavy () function is triggered, and when the setInterval method is called, this function does not work immediately, the steps are counted, the calls go evenly one after another. That is why setInterval is faster?

  • one
    If you add some console.log to doSomethingHeavy, you will see that it works in both cases (why it doesn’t work) - andreymal
  • learn.javascript.ru/settimeout-setinterval#setinterval Scroll down a bit, there are pictures - Dmytryk
  • one
    with setInterval - the function execution time is not taken into account, with setTimeout - each new start is planned only after the end of the current one - Dmytryk
  • Well, then explain to me why in the doSomethingHeavy function for? And where does this number 25 come from? Why is 25? - ZdraviSmisl
  • one
    @ZdraviSmisl according to the name of the function, it does hard work. The number 25 is taken just as the best option for hard work. - Stepan Kasyanenko

0