Home > Web Front-end > JS Tutorial > body text

Detailed explanation of native JS asynchronous and single-threaded

小云云
Release: 2018-03-07 14:40:50
Original
1840 people have browsed it

What is asynchronous (versus synchronous)? This article mainly shares with you the detailed explanation of native JS asynchronous and single-threaded. I hope it can help everyone.

//异步
console.log(100);
setTimeout(function(){
console.log(200);
},1000);
console.log(300);
//同步
console.log(100);
alert(200);
console.log(300);//同步会阻塞等待
Copy after login

When is asynchronous required?

--When waiting may occur

--During the waiting process, the execution of the program cannot be blocked like alert

--So all "waiting situations" require asynchronous

Scenarios where the front-end uses asynchronous

Scheduled tasks:

setTimeout/setInterval
console.log(100);
setTimeout(function(){
console.log(200)
},1000);
console.log(300);
//同步
console.log(100);
alert(200);
console.log(300);
网络请求:ajax请求,动态<img>加载
//ajax
console.log(&#39;start&#39;);
$.get(&#39;xxx&#39;,function(){
console.log(data);
})
console.log(&#39;end&#39;);//startenddata
//img
console.log(&#39;start&#39;);
var img = document.creatElement(&#39;img&#39;);
img.onload = function(){
console.log(loaded);
}
img.src = &#39;xxxxxxxxxxxxxxxx&#39;;
console.log(&#39;end&#39;)//startendloaded
事件绑定
console.log(&#39;start&#39;);
var btn1 = document.getElementById(&#39;btn1&#39;);
btn1.addEventListener(&#39;click&#39;,function(){
console.log(&#39;clicked&#39;);
})
console.log(&#39;end&#39;)
异步和单线程
同步和异步的区别?分别举一个同步和异步的例子
同步会阻塞代码执行,而异步不会
alert是同步,setTimeout是异步
一个关于setTimeout的笔试题
console.log(1);
setTimeout(function(){
console.log(2)
},0);
console.log(3);
setTimeout(function(){
console.log(4);
},1000);
console.log(5);
//13524
Copy after login

What are the scenarios where the front-end uses asynchronous

Scheduled tasks: setTimeout, setInterval

ajax request, img loading

Event binding

Related recommendations:

Example detailed js Asynchronous programming

Several JavaScript asynchronous loading related issues

Detailed explanation of single-threaded JS execution issues

The above is the detailed content of Detailed explanation of native JS asynchronous and single-threaded. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!