C
C
Caretaker2018-09-18 17:49:52
Node.js
Caretaker, 2018-09-18 17:49:52

Why does setInterval eat more CPU than setTimeout?

Hello community.
I came across an extremely interesting situation in one of the modules. I'll put it in a short format ...
Code option 1:

const timer = setInterval(() => {
  periodicFunction();
}, 1000);

periodicFunction() {
  ...рабочий код функции...
};

Code option 2:
periodicFunction();

periodicFunction() {
  const timer = setTimeout(() => {
    clearTimeout(timer);
    periodicFunction();
  }, 1000);

  ...рабочий код функции...
};

In fact, they are almost the same - every second a function is called, it does some work (it just reads a small JSON file in asynchrony and parses it into a variable).
However, I encountered an effect that is absolutely incomprehensible to me:
- code option 1 (one-time setInteval call) loads the processor by 10% locally and almost 40% on the server
- code option 2 (periodic setTimeout call) loads the processor by no more than 1% locally and 1.5 % on the server
Any guesses as to the reason for this strange behavior?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Caretaker, 2019-02-21
@zuart

After the update, I don’t know which account NODE stumbled upon old test scripts that emulated the problem. I decided to repeat the tests - the problem is not reproduced. Apparently the "root of evil" was in a specific version ...

P
Pavlo Ponomarenko, 2018-09-18
@TheShock

Put console.log( counter++ )in your periodicFunction, see how many times it is actually called. setTimeoutand setIntervaldo not eat the processor by themselves, especially up to 40%.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question