Note: This article is excerpted from the book "Secrets of the JavaScript Ninja" by John Resig . I translated it for everyone's learning only. Please correct me if there are any deficiencies in the translation.
This article mainly explains the timer from the following aspects:
Timers are something we understand little about and are often abused. They are a feature of JavaScript. In fact, it can help us a lot in complex application development. Timers provide the ability to asynchronously delay the execution of code fragments. JavaScript is inherently single-threaded (only part of the js code can run within a certain time range). Timers provide us with a way to avoid this limitation. method, thus opening up another way to execute the code.
Interestingly, contrary to commonly accepted belief, timers are not part of the JavaScript language, but are part of the methods and objects introduced by the browser. This means that if you choose to run it in a non-browser environment, chances are the timer won't exist and you'll have to implement your own version using specific functionality (such as Rhino threads).
1. How the timer works
Fundamentally, it's important to understand how timers work. Often the behavior of a timer is not intuitive because it is in a separate thread, let's start with a test of three functions, for each of which we have the opportunity to build and control the timer.
In order to understand how timers work internally, there is an important concept that needs to be discussed: delays are not guaranteed. Since all JavaScript in the browser runs in a single thread, asynchronous events (such as mouse clicks, timers) will only run when there is an open state during execution. The following example illustrates this problem well:
There is a lot of information to digest in this diagram, understanding it fully will give you a better idea of asynchronous js execution, the diagram is one dimensional, in the vertical direction is time (wall clock), measured in milliseconds. The blue box represents the proportion of js execution. For example, the first javascript block takes about 18 seconds to run, the mouse click takes about 11 seconds and so on.