Here's a more-or-less-but-rather-more elegant solution using a generator function.
Generator functions are useful here, as their execution can be paused by yield
, and resumed by calling the generator object's next
method:
function* logger() {
while (true) {
for (let index = 0; index < 4; index++) {
console.log(index)
yield
}
}
}
let generator = logger()
setInterval(() => generator.next(), 1000)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…