利用 Promise 實(shí)現(xiàn)一個(gè)元素先紅色兩秒在黃色一秒再綠色三秒,不斷循環(huán)。目前我想出的有三種方法座柱。
首先是 HTML 代碼:
<table>
<tbody>
<tr>
<td class="light"></td>
</tr>
</tbody>
</table>
1.第一種方法渠啊,這段代碼其實(shí)只是利用了 setTimeout 的特性输吏,只用 setTimeout 也可以實(shí)現(xiàn)。
let light = document.querySelector('.light');
function red() {
return new Promise(function(resolve, reject) {
light.style.backgroundColor = 'red';
setTimeout(function() {
resolve(green())
}, 2000);
})
}
function green() {
return new Promise(function(resolve, reject) {
light.style.backgroundColor = 'green';
setTimeout(function() {
resolve(yellow())
}, 3000);
})
}
function yellow() {
return new Promise(function(resolve, reject) {
light.style.backgroundColor = 'yellow';
setTimeout(function() {
resolve(red())
}, 1000);
})
}
red();
2.第二種方法替蛉,利用 Promise 和 async 函數(shù)的特性贯溅,是代碼看起來更像是同步。
let light = document.querySelector('.light');
function lightChange(duration,color) {
return new Promise(function(resolve,reject) {
light.style.backgroundColor = color;
setTimeout(resolve,duration);
})
}
async function index() {
while(1) {
await lightChange(2000,'red');
await lightChange(1000,'yellow');
await lightChange(3000,'green');
}
}
// async 函數(shù)提供了用同步代碼編寫異步的方式
index();
3.第三種方法用生成器和迭代器模擬 async 函數(shù)躲查。這種寫法并沒有什么意義它浅,只是寫著玩,不推薦使用镣煮。
let light = document.querySelector('.light');
function func(color, duration) {
return new Promise(function(resolve, reject) {
light.style.backgroundColor = color;
setTimeout(function() {
it.next();
}, duration)
})
}
function* main() {
while (1) {
yield func('red',2000);
yield func('yellow',1000);
yield func('green',3000);
}
}
var it = main();
it.next();
Gwen Weustink 2016-03-02 09-53-30 .jpg