function red() {
console.log("red");
}
function green() {
console.log("green");
}
function yellow() {
console.log("yellow");
}
const light = function (timer, cb) {
return new Promise((resolve) => {
setTimeout(() => {
cb();
resolve();
}, timer);
});
};
const trafficSignal1 = function () {
Promise.resolve()
.then(() => {
return light(3000, red);
})
.then(() => {
return light(1000, green);
})
.then(() => {
return light(2000, yellow);
})
.then(() => {
return trafficSignal();
});
};
const trafficSignal2 = function () {
let lightSetting = [
{ behavior: red, interval: 3000 },
{ behavior: green, interval: 1000 },
{ behavior: yellow, interval: 2000 },
];
const reducer = (accumulator, currentValue) => {
return accumulator.then(() =>
light(currentValue.interval, currentValue.behavior)
);
};
return lightSetting
.reduce(reducer, Promise.resolve())
.then(() => trafficSignal2());
};
const timer = (count = 0) =>
setInterval(() => {
count++;
console.log(count);
}, 1000);
const setup = () => {
timer();
trafficSignal2();
};
setup();
console