Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand JavaScript single thread and setTimeout timer

2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to understand JavaScript single thread and setTimeout timer? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.

Understanding JavaScript's single-threaded philosophy is important for JavaScript learning and for mastering some of the design mechanisms, such as callbacks and timers. It is also of great help to the follow-up study of NodeJS.

Through the form of first demo, then summary, it makes the single thread of JavaScript easier to understand.

1 var a = 1; / Global variable a 2 function test () {3 var astat2; / / variable a 4 setTimeout in test (function () {5 alert (a); / / variable a 6 aq3 in output test; / / modify variable a 7} in test, 3000); 8 aq4; / modify variable a 9 setTimeout in test (function () {10 alert (a)) / / output variable a 11 aq5 in test; / / modify variable a 12}, 1000) in test; 13 alert (a); / output variable a 14} 15 test () in test; / / execute test function 16 alert (a) / / output global variable a / / run result: 4 1 4 5 / * result parsing: first output test () run result 4, then output 1 of the next line of code, and then 1000ms output the variable in test () and then output the variable in test () after 3000ms * / / * operating mechanism: 1. JavaScript is a single thread Execute from top to bottom. 2. The setTimeout asynchronous method is stored in the task queue. After the execution of the JS main thread is completed, the tasks in the task queue will be executed in the JS main thread! -> execute 15 lines first, then execute 16 lines-> execute 15 lines, call the test () method-> call the test () method, first create a variable, then put * setTimeout into the corresponding thread of setTimeout to execute (start timer timer), line 8, modify the variable an in test to 4, then add the second setTimeout to the thread queue corresponding to setTimeout, execute 13 lines, and output the variable an in test. This time it is 4 Then 16 lines are executed, and the global variable an is output. After 1.-> 1000ms, the callback function of the second setTimeout is added to the JS task queue. After 3000ms, the callback function of * setTimeout is added to the JS task queue. -> after the main JS thread completes execution, it executes the event of the task queue. The second setTimeout first enters the task queue, so priority execution, execution line 10, output variable an in test, value 4, and then di11 line, change variable an in test to 5. After 2000ms, * setTimeout enters the task queue, and the JS main thread stack is empty, so add it to the JS main thread for execution, line 5, the variable an in the output test, the value of the variable is 5, and line 6 modifies the test variable a to 3. * /

This extends the following code:

Var a = 1; var date = + new Date (); / / Tips: convert to integers function test () {var aqum2; setTimeout (function () {console.log (aplomb) + (new Date ()-date)); aplomb 3;}, 3000); axi4; setTimeout (function () {console.log (aura) + (new Date ()-date)); axi5 }, 1000); console.log (new Date ()-date));} while (new Date-date So: JavaScript is a single thread).

2. JavaScript tasks are divided into two types: synchronous tasks and asynchronous tasks. Synchronous task: for a task queued on the main thread, the next task will not be executed until the previous task has been completed. Asynchronous tasks: for tasks that enter the "task queue" instead of entering the main thread, only the "task queue" notifies the main thread that a task queue can be executed, and the task queue will enter the main thread for execution until the main thread is completed. -> So: as long as the main thread is empty, it will read the "task queue". This is the operation mechanism of JavaScript.

3. The main thread reads events from the "task queue". This process is continuous, so the whole event is also called "event cycle" (Event Loop).

HTML5 specifies that the minimum value (minimum interval) of the second parameter of setTimeout () must not be lower than 4ms, and will automatically increase if it is lower than 4ms. Prior to this, the minimum time for browsing in the old version was set to 10ms. In addition, for those DOM changes (especially those parts of the design page that are re-rendered), they are usually not performed immediately, but once per 16ms. It is better to use requestAnimationFrame () than to use setTimeout ().

4. It should be noted that setTimeout only inserts events into the "event queue", and the main thread will not execute the callback function specified by him until the previous code (execution stack) is finished. If the current code takes a long time, it may take a long time, so there is no guarantee that the callback function will execute at the time specified by setTimeout ().

Javascript is single-threaded, which means all tasks need to be queued. All tasks are then divided into two categories: synchronous tasks and asynchronous tasks! Synchronous task: a task executed on the main thread will be executed only if the previous task is completed! Asynchronous task: a task that enters the "task queue" without entering the main thread.

Js is single-threaded, but browsers are multithreaded! Browsers are event driven!

JS runs in the browser and is single-threaded, with one JS thread per window, but the browser is not single-threaded. There may be multiple threads as follows:

Javascript engine thread, interface rendering thread, browser event trigger thread, Http request thread.

SetTimeout can change the order in which js is executed. For example, if we want to output Hello World,world, we must output it after hello, regardless of the order of our code, we can use setTimeout to output the same effect.

/ / Code 1: var date = + new Date (); console.log ('Hello',new Date ()-date); setTimeout (function () {console.log (' world',new Date ()-date);}, 500); / / Code 2: var date = + new Date (); setTimeout (function () {console.log ('World',new Date ()-date);}, 500); console.log (' Hello',new Date ()-date) / / the result of the above two codes is the same, the result is: output Hello first, then 500ms and then output World! [actual operation: 501ms]

The timer in the browser is also a thread!

Javscript is single-threaded, and ajax requests are indeed asynchronous! The reason is that when an ajax request is made, it is executed in the browser's Http request thread, and the callback function after execution is executed in the Javascript thread!

Summary:

Javascript is single-threaded, and browsers are multithreaded. Browser threads include JS engine threads, interface rendering threads, browser event threads, and Http request threads. However, the threads provided by different browsers are different. Generally speaking, the JS engine thread and the interface rendering thread are mutually exclusive, and the two threads cannot be executed at the same time, otherwise, there will be a contradiction between the interface rendering thread and the JS thread modifying the same DOM style!

This is the answer to the question about how to understand JavaScript single thread and setTimeout timer. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report