Timing in JS - multiple setIntervals running at once and starting at the same time?

前端 未结 5 2393
忘了有多久
忘了有多久 2020-12-14 16:53

Let\'s say I have a function:

myFunc = function(number) {
  console.log(\"Booyah! \"+number);
}

And I want it to run on a set interval. Sou

5条回答
  •  太阳男子
    2020-12-14 17:26

    Good question, but in JS you can't. To have multiple functions in the same program execute at the same time you need multi-threading and some deep timing and thread handling skills. JS is single threaded. 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. Multiple intervals/timeouts are all adding calls to the same event stack, so they run in turn as the proc is available.

提交回复
热议问题