function red(){
console.log('red');
}
function green(){
console.log('green');
}
function yellow(){
console.log('yellow');
}
1.实现一个函数来时间控制(promise)
var tic = function(timer, fun) {
return new Promise(function(resolve) {
setTimeout(function() {
fun()
resolve()
}, timer)
})
}
2.方法1:使用Promise去循环
var step1 = function() {
tic(3000, red).then(function() {
return tic(2000, green)
}).then(function() {
return tic(1000, yellow)
}).then(function() {
step1()
})
}
step1()
2.1方法2:利用Generator来减少回调
function *gen(){
yield tic(3000, red);
yield tic(1000, green);
yield tic(2000, yellow);
}
var iterator = gen();
var step2 = function(gen, iterator){
var s = iterator.next();
if (s.done) {
step2(gen, gen());
} else {
s.value.then(function() {
step2(gen, iterator);
});
}
}
step2(gen, iterator);
网友评论