认识JavaScript的单线程
说明
在JavaScript中可以“并发”处理很多任务,虽然JavaScript是单线程,但是其异步特性使得可以处理“并发任务”,其原理就是JavaScript中有一个事件循环队列,如果当前代码块不具有原子性(即是异步的),就会将该代码块的任务添加到事件循环队列中,当JavaScript引擎调用完毕原子代码块的任务队列时,便会从事件循环队列中获得队列的最前面的任务,将他压入执行队列中。为了清除的认识到这个特性,于是乎写了一个动画来清除的认识。
代码示例
不多说,下面上代码(简单易懂)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<style>
.box1{
width: 200px;
height: 200px;
border-radius: 50%;
background-color: gold;
position: fixed;
}
.box2{
width: 200px;
height: 200px;
border-radius: 50%;
position: fixed;
background-color: seagreen;
}
.btn-box{
margin-top: 200px;
}
</style>
</head>
<body>
<div id="box" class="box1" style="left:0px;top:0px"></div>
<div class="btn-box">
<button id="move">移动</button>
<button id="start">开启额外任务</button>
</div>
<script>
var box = document.getElementById("box");
var start = document.getElementById("start");
var move = document.getElementById("move");
move.addEventListener("click", function () {
/** moveBasice()
@ param el 移动元素
@ param direction 移动方向
@ param distance 移动距离
每 10ms 移动 1px
*/
function moveBasic(el, direction, distance) {
var position = parseInt(el.style[direction]);
if (position < distance) {
position ++;
el.style[direction] = position + 'px';
setTimeout(() => {
moveBasic(el, direction, distance);
},10);
}
}
moveBasic(box, 'left', 1000);
});
start.addEventListener("click", function () {
/** 函数 duty()
主要是为了使得该任务执行时间很多,大于 1 ms,
从而使事件循环队列中的元素移动任务等待,以明显看出效果
*/
function duty() {
var arr = [];
for (var i = 0; i < 8000000; i++) {
arr.push(i);
}
setTimeout(() => {
duty();
}, 1);
}
duty();
});
</script>
</body>
</html>
运行
新建一个 HTML 文件,将代码复制进去,之后用浏览器打开该文件,注意:代码中用了一些 es6 的语法,所以最好使用较新的浏览器。打开之后先点击移动,可以看到元素缓缓的移动。之后刷新界面,然后先点击开启额外任务,然后再点击移动,你会发现元素移动卡卡的。你可以在代码中看到,duty 函数的作用。之后便能清楚的认识到JavaScript 的单线程。