2

I'm getting some (to me) unexpected behavior with this code:

setInterval(function() {
  console.log('Interval running');

  setTimeout(function() {
    console.log('TimeOut called');
  }, 5000);

}, 2000);

setInterval is running fine (every 2 seconds), but setTimeout runs fine only first time (after 5 seconds) and after that it's starts running after 2 seconds also? :/

What am I missing here?

Rick
  • 4,030
  • 9
  • 24
  • 35
Goran D
  • 43
  • 1
  • 7
  • I think it is running correctly but there is no way to distinguish which `TimeOut called` got consoled for which `setInterval` call – brk Jul 16 '18 at 08:15

2 Answers2

3

Every 2 seconds, you set a timeout for something to happen 5 seconds later from that point in time.

That means the events will happen at

  • 2 + 5 = 7 seconds
  • 4 + 5 = 9 seconds
  • 6 + 5 = 11 seconds
  • ... etc.

which is the behavior you're seeing.

AKX
  • 152,115
  • 15
  • 115
  • 172
1

According to setInterval doesn't acutally run the function after the delay, rather after the delay it adds the function to the event stack to be run as soon as the processor can get to it. If the proc is busy with another operation, it will take longer than the delay period to actually run. So you get that delay.

setInterval(function() {
  console.log('Interval running');

  setTimeout(function() {
    console.log('TimeOut called');
  }, 5000);

}, 2000);
263
3VM527:2 Interval running
VM527:5 TimeOut called
VM527:2 Interval running
VM527:5 TimeOut called
VM527:2 Interval running
VM527:5 TimeOut called
VM527:2 Interval running
Anamnian
  • 417
  • 4
  • 20