Home  >  Article  >  Web Front-end  >  JS timer and single-threaded asynchronous features

JS timer and single-threaded asynchronous features

不言
不言Original
2018-07-07 10:05:001747browse

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);//清除定时

The timer is indeed very easy to use, but it is not easy to use. Why do you say this?

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)

Why is this? As mentioned before, JS will process the timer event asynchronously, which means that it will not wait for the timer event

to be processed before executing the following code, but directly insert the timer event into the event After entering the queue, directly execute the code below

. When the timer event is completed, JS will turn around and execute the callback part of the timer event code. This is asynchronous!

Asynchronous can effectively prevent JS threads from being blocked, and it will be very efficient, allowing JS to do more things with limited resources. This is amazing. of. (We will be exposed to a lot of asynchronous issues in node)

The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

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!

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