https://www.cnblogs.com/dojo-lzz/p/5495671.html
这是阅读这篇博文记下的笔记
红灯三秒亮一次,黄灯1秒亮一次,绿灯2秒亮一次,,如何让三个灯不断交替重复亮灯
light函数返回一个Promise状态,当Promise状态从Pending => fulfilled,step才会执行下一个then。这里使用递归,不使用循环是因为JavaScript的时间循环机制,因为setTimeout 属于microtask,会被挂起,直到主线程的循环结束后才执行,这样循环就会一直空循环。
实现队列实现
<!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>
<style>
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
#light {
width: 100px;
height: 100px;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="light"></div>
<script>
var lightStyle = document.querySelector("#light").style;
function setColor (color, time) {
return function (callback) {
lightStyle.backgroundColor = color;
setTimeout(callback, time);
}
}
// 这里接受的是一个函数数组
var queue = function (func) {
// next()是一个自执行函数
(function next () {
if(func.length > 0) {
// shift()从头删除一个元素
var f = func.shift();
f(next);
}
})();
};
var setRedColor = setColor("red",3000);
var setYellowColor = setColor("yellow",1000);
var setGreenColor = setColor("green",2000);
// 也是一个自执行函数,从函数不停执行
+function tick () {
queue([
setRedColor,
setYellowColor,
setGreenColor,
tick
])
}()
</script>
</body>
</html>
+function () {} ()
// 相当于自执行函数
(function() {}) ()
对大神的写法暂时不理解,已将目前的理解写在注释上,个人不太喜欢这种炫技的写法。
还有迭代器写法,日后更新。