Home >Web Front-end >JS Tutorial >Detailed introduction to how JavaScript timers work

Detailed introduction to how JavaScript timers work

php是最好的语言
php是最好的语言Original
2018-08-09 10:22:501420browse

How JavaScript timer works

Tags (space separated): JavaScript timer


Recently looking at ajax principle When I was working, I saw a foreign article that explained the working principle of JavaScript timer, which helped me understand the single-threaded working mode of js well. Translate it here for your reference, original address.
Translation text
Fundamentally speaking, it is very important to understand how JavaScript timers work. Usually js behaves in a single thread. Let's first look at the three functions that can construct and operate timers.

 - 启动单个定时器,在延迟后调用指定的功能。该函数返回一个唯一的ID,该Id可以用于取消定时器    var id = setTimeout(fn, delay); 
 - 类似setTimeout但不断地调用函数(每次都有延迟),直到它被取消,类似于定时任务。同上也返回唯一ID用于取消定时器    var id = setInterval(fn, delay); 
 - 接受计时器ID(由上述任一功能返回)并停止触发计时器回调。
    clearInterval(id);
    clearTimeout(id);

In order to understand the inner workings of timers, we need to explore an important concept: timer delays are not guaranteed to be accurate. Since all JavaScript in the browser executes on a single thread, asynchronous events (such as mouse clicks and timers) only run when they can be executed. This is best demonstrated using a diagram, like this:

Detailed introduction to how JavaScript timers work

There is a lot of information to understand in this diagram, and understanding it completely will give you a better understanding of asynchronous JavaScript The way execution works. This graph is one-dimensional: vertically, we have (wall clock) time in milliseconds. The blue box indicates the portion of JavaScript being executed. For example, the first JavaScript block takes about 18ms to execute, a mouse click on the block takes about 11ms, and so on.

Because JavaScript can only execute one piece of code at a time (determined by its single-threaded nature), each block of code "blocks" the progress of other asynchronous events. This means that when an asynchronous event occurs (such as a mouse click, a timer firing, or an XMLHttpRequest completing), it is queued for later execution (the way this queuing actually occurs depends on the browser) Browsers vary, here is a brief explanation).

First, in the first block of JavaScript, start two timers: 10ms setTimeout and 10ms setInterval. Because of where and when the timer starts, it actually fires before we actually complete the first block of code. But note that it will not be executed immediately (it cannot do this due to threads) but will be queued to be executed at the next available moment.

Also, in the first JavaScript block, we see the mouse click. The JavaScript callback associated with the mouse click event (we never know when the user performs an action, so it is considered asynchronous) cannot be executed immediately, so, like the initial timer, it is queued to be executed later.

After the initial block of JavaScript is completed, the executing browser will immediately ask: What tasks are waiting to be executed in the queue? In this case, both the mouse click handler and the timer callback are waiting. The browser then selects one (mouse click callback) and executes it immediately. The timer will wait until the next time it is taken out of the queue for execution.

Please note that when the mouse click handler is executed, the first interval callback is executed. Like a timer, its handler is queued for later execution. However, please note that when the interval is triggered again (when executing the timer program), the interval callback of Interval is discarded (Translator's Note: I don't understand it very well here, please leave a message to exchange advice. Is it because there is already an interval queued? ). If you want to call an interval callback while executing a large chunk of code, the interval callbacks will be added to the task queue consecutively, with no delay between them. Browsers often simply fetch tasks from the queue until there are no more tasks in the queue.

In fact, we can see that the third interval callback fires while the interval itself is executing. This shows us an important fact: Intervals don't care what is currently executing, they queue indiscriminately.

Finally, after the second interval callback has finished executing, we can see that the JavaScript engine has no tasks to perform. This means that the browser is now waiting for a new asynchronous event to occur. When the interval fires again, it's at the 50ms position. However, this time, no program is executing, so it gets triggered immediately.

Let's look at an example to better illustrate the difference between setTimeout and setInterval.

setTimeout(function(){
  /* Some long block of code... */
  setTimeout(arguments.callee, 10);
}, 10);

setInterval(function(){
  /* Some long block of code... */}, 10);

These two pieces of code may seem functionally equivalent at first glance, but they are not. It's worth noting that the setTimeout code always has a delay of at least 10ms after the previous callback execution (it may end up being more, but never less than 10ms), while setInterval tries every time during this long code execution. A callback is executed every 10ms (Translator's Note: It can be understood that during the execution of this long code, a task will be added to the queue every 10ms, with no interval in between).

We learned a lot here, let’s review:

The JavaScript engine has only one thread, forcing asynchronous events to be queued for execution.
setTimeout and setInterval are fundamentally different in how they execute asynchronous code.
If the timer is blocked from executing immediately, it will be delayed until the next possible execution point (which will exceed the required delay).
If the execution time of the callback program in setInterval is long enough (exceeds the specified delay), the interval can be executed without delay (Translator's Note: Because another callback will be added when a callback has not finished running).
All of this is very important knowledge to understand how the JavaScript engine works, especially when a large number of asynchronous events occur, laying the foundation for building advanced application code.

Related recommendations:

javascript timer working principle

About the analysis of the principle of timer in JavaScript

The above is the detailed content of Detailed introduction to how JavaScript timers work. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn