0%

JS 红黄绿灯交替

用回调的方式执行

1
2
3
4
5
6
7
8
9
10
11
const run = (time, color, callback) => {
setTimeout(() => {
console.log(color);
callback && callback();
}, time);
};

let loop = () =>
run(1000, 'red', run(2000, 'green', run(3000, 'yellow', loop)));

loop();

后记

我开始写成这样了,知道错在哪儿了吗?

1
2
3
4
5
6
7
const run = (time, color, callback) => {
setTimeout(() => {
console.log(color);
callback && callback();
}, time);
};
let loop = run(1000, 'red', run(2000, 'green', run(3000, 'yellow', loop)));