Skip to content

JavaScript 红黄绿灯交替实现

Published: at 01:28 PMSuggest Changes

用回调的方式执行

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();

后记

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

const run = (time, color, callback) => {
  setTimeout(() => {
    console.log(color);
    callback && callback();
  }, time);
};
let loop = run(1000, 'red', run(2000, 'green', run(3000, 'yellow', loop)));

Previous Post
JavaScript 出现频率最高的单词
Next Post
JavaScript AJAX 实现详解