This article mainly introduces the JS timer and single-thread asynchronous features. It has certain reference value. Now I share it with you. Friends in need can refer to it.
The first thing to say is, timing The methods related to the timer are all BOM methods, and the timer is used to execute a piece of code within a set time, or to repeat the code within a given time interval. Specific function:
setTimeout(callback, delay);//delay一定的时间后,执行回调函数只执行一次 setInterval(callback, delay);//每隔一段时间执行一次callback,反复执行 clearInterval(timer);//清除定时
We know that JS is single-threaded. Since it is single-threaded, it is easy for the thread to be blocked. How to solve
? --asynchronous!
Of course, JS is single-threaded and cannot be asynchronous, but the host environment of JS (such as browser, node) is multi-threaded
, and the host environment is driven in some way (for example: node's event-driven) This makes JS have asynchronous features.
Why are we suddenly talking about single-threaded asynchronous JS? Because the timer event will be processed asynchronously by JS, what does it mean?
In code:
var num = 1; setTimeout(function() { num++; console.log(num); }, 1000); console.log(num); //结果并是不(2,1)而是(1,2)
JS Asynchronous Programming Promise, Generator, async/await
Introduction to JS Asynchronous Programming
The above is the detailed content of JS timer and single-threaded asynchronous features. For more information, please follow other related articles on the PHP Chinese website!