我有一个小脚本,按顺序打开和关闭3个LED。它运作良好,但我想延迟每次点亮之间的时间。
例如,我希望红色LED亮起然后关闭2秒钟,然后再转到下一个LED。
function delay() {
return new Promise(resolve => setTimeout(resolve, 500)); //the delay between LED light ups. I'd like to add a delay between the delay.
}
async function delayedLog(item) {
await delay();
console.log(item);
LED_RED.off();
LED_GREEN.off();
LED_YELLOW.off();
}
async function processArray(array) {
for (const item of array) {
if(item===1){LED_RED.on();}
if(item===2){LED_GREEN.on();}
if(item===3){LED_YELLOW.on();}
await delayedLog(item);
}
console.log('Done!');
}
processArray([1,3,1,3,1,2,3,2,1,2,1,2,3,2,1,3]); //numbers represent LEDs. 1 is red, 2 is green and 3 is yellow.
});
答案 0 :(得分:4)
首先,您可以修改延迟功能以接受具有延迟持续时间的参数:
function delay(duration) {
return new Promise(resolve => setTimeout(resolve, duration));
}
由于您使用的是async / await语法,因此您可以在任何地方添加延迟:
async function delayedLog(item) {
await delay(500);
console.log(item);
LED_RED.off();
await delay(2000);
LED_GREEN.off();
await delay(1000);
LED_YELLOW.off();
} // use your imagination
答案 1 :(得分:0)
您可以使用generator和promises将数字数组处理为异步操作。
原始方法的问题在于promises只解析一次,但您需要异步处理值流。
class LED {
constructor(number, color) {
this.number = number
this.color = color
}
on() {
console.log(`${this.number} ${this.color} on`)
}
off() {
}
}
const LED_RED = new LED(1, 'red')
const LED_GREEN = new LED(2, 'green')
const LED_YELLOW = new LED(3, 'yellow')
// run the given generator in sequence
function run(generator) {
let ret
(function iterate(val) {
// run the next iteration of the generator
ret = generator.next(val)
if (!ret.done) {
// the generator returns promises so call the promise
ret.value.then(iterate)
}
else {
console.log('Done!')
}
})()
}
// call the switching of lights after 2000ms
function delay(val) {
return new Promise(
resolve => setTimeout(() => {
LED_RED.off()
LED_GREEN.off()
LED_YELLOW.off()
switch (val) {
case 1: LED_RED.on(); break
case 2: LED_GREEN.on(); break
default: LED_YELLOW.on()
}
resolve(val)
}, 2000)
)
}
// generator to process the array of numbers
function *processArray(items, cb) {
while (items.length) {
// the execution of your program will pause here while each
// item is processed by your delay
yield delay(items.shift())
}
}
run(
processArray(
[1,3,1,3,1,2,3,2,1,2,1,2,3,2,1,3]
)
)