preface

Paragraph of time just watching the “JS ninja secrets”, although is 15 years, some things are out of date, but as the prototype chain, closure, such as regular, timer mechanism is not out of date, inside a lot of things are very fine, is well worth reading, the book will be on the interpretation of part timer mechanism in detail, If you like, you can click Bozam/follow, support, hope you can have a harvest after reading this article.

Personal blog: obkoro1.com


To prepare

Before reading this article, it is recommended to read the Js Event Loop mechanism and explain it with examples to understand what is going on behind the scenes. The Event Loop mechanism will not be explained in detail in this article.

Problems solved by timer:

Due to the single-threaded nature of JS, timers provide a way out of the single-threaded limit by letting a piece of code execute asynchronously after a certain number of milliseconds.

Set and clear timer:

A direct quote from the Ninja Cheats:

Note:

  1. The timer interval is set to 0 and there is also a delay of a few milliseconds.
  2. In the use ofsetTimeoutandsetIntervalIt is best to assign it to a variable in order to cancel the timer.
  3. In the use ofVueThe time,setTimeoutandsetIntervalThis points to the Window object and does not access component data or methods.
  4. In the use ofVueRoute hops are not destroyedsetInterval, but the component has been destroyed, which can cause problems.
  5. In the execution threadsetTimeout/setIntervalNot guaranteed to execute the callback function on time.
  6. setIntervalThe call may be discarded as wellsetIntervalContinuous execution of

The solutions to point 3 and point 4 can refer to several problems in Vue practice that I wrote about earlier.

The next point is the fifth and sixth point, which are the most important and the main content of this article.

Timer execution in the execution thread

Here’s chestnuts from Ninja Secrets:

Let’s see what’s happening here:

  1. First, there is an 18-millisecond JS block to execute at 0 milliseconds.
  2. Then I set two 10-millisecond timers at 0 milliseconds,setTimeoutAs well assetInterval.setTimeoutThe first set.
  3. There was a mouse click event at the sixth millisecond.

Event queuing.

So many things are happening at once, and due to the single-threaded nature of JS, when a thread is in execution state and an asynchronous event is fired, it is queued and executed only when the thread is idle.

Asynchronous events include mouse clicks, timer triggers, Ajax requests, promises, and so on.Copy the code

Let’s go back to chestnuts:

There is an 18-millisecond block of code to execute, and only that block can be executed during that 18-millisecond period. Other events are queued up for execution after they fire.

While the code block was still running, a mouse-click event occurred in ms 6, and two handlers, setTimeout and setInterval, occurred in ms 10. These three events could not be executed immediately, but were added to the queue waiting to be executed.

First in, first out (first queued, first executed)

At 18 ms, the code block finishes execution, and three tasks are queued for execution. According to the first-in, first-out principle, the click event will be executed first, and setTimeout and setInterval will be queued for execution.

The setInterval call is deprecated

At the time of the click event, the second setInterval also expires at the 20th millisecond, because the click event has already occupied the thread, so the setInterval still cannot be executed, and because there is already a setInterval queued for execution, So this time the setInterval call will be discarded.

Browsers do not add the same setInterval handler to the queue more than once.

setTimeout/setIntervalThere is no guarantee that callback functions will be executed on time

The click event ends execution at the 28th millisecond, and two tasks (setTimeout and setInterval) are waiting to be executed. Following the first-in-first-out principle, setTimeout is set earlier than setInterval, so setTimeout is executed first.

So: The setTimeout handler we expect to execute at ms 10 ends up executing at ms 28, which is why the setTimeout/setInterval mentioned above is not guaranteed to execute the callback on time.

At 30 ms, setInterval fires again, invalidated because there are already setIntervals queued in the queue.

Continuous execution of setInterval

At 36th ms, the setInterval handler in the queue starts executing. SetInterval takes 6 milliseconds to execute.

At the 40th millisecond, setInterval will be triggered again, because the last setInterval is being executed and no setInterval is queued, and the setInterval triggered this time will be queued.

Therefore, the processing duration of setInterval cannot be longer than the setInterval; otherwise, setInterval will be executed repeatedly without interval

At 42nd ms, the first setInterval ends, and then the setInterval in the queue starts execution immediately, finishing execution at 48ms. SetInterval is then fired again at 50 milliseconds, at which point no tasks are queued and will be executed immediately.

SetTimeout Indicates that a timer is triggered periodically at a specified interval.

As mentioned above, setInterval must not be longer than the setInterval, otherwise setInterval will repeatedly execute without interval.

In many cases, we don’t have clear control over how long the process takes. In order to trigger the timer periodically at regular intervals, ninja Cheats provide the following use method:

// I've actually seen this technique in many places, not just in Ninja Secrets. setTimeout(function repeatMe(){ // do something setTimeout(repeatMe,10); // After executing the contents of the handler, call the program at the end of the 10ms interval, so that it is guaranteed to be a 10ms cycle},10)Copy the code

Other tips on timers from Ninja Cheats:

  • Timer can not be very fine grained control execution time, the book recommends more than 15ms.
  • You can use timers to break down long-running tasks, which you can Google here.

Is a task queue as simple as queuing?

In fact, the task queue is not just a simple queue, but it is mentioned in the Ninja Secret book that this concept is used for convenience. If you want to have a clearer understanding of the mechanism behind it, it is recommended to read again: Js Event Loop mechanism and example explanation.


conclusion

All of this is caused by the single-threaded nature of JS, so there are events queueing, fifO, setInterval calls being discarded, timers not being able to execute callback functions on time, and setInterval sequential execution. Keep this in mind and many questions about the sequence of events can be made sense. And find a solution.

I hope the friends can click like/follow, your support is the biggest encouragement to me.

Personal blog and nuggets personal homepage, if need to reprint, please put the original link and signature. Code word is not easy, thank you for your support! I write articles in line with the mentality of exchange records, write bad place, do not quarrel, but welcome to give directions.

If you like this article, please follow my subscription number, long technical road, looking forward to learning and growing together in the future.

The above 2018.6.17

References:

JS Ninja Secrets Chapter 8: Tame threads and timers