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:
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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools