问题
I have the following loop:
for (let index = 0; index < 4; index++) {
setInterval(function() {
console.log(index)
}, 1000);
}
How can I make it so that it console logs 0 the first second, 1 the second second, 2 the third second, 3 the fourth second, 0 the fifth second, and so on until the interval is cleared?
回答1:
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)
Or, again with generators, you can even yield
the current index
, and let the interval function log (or do anything else with) it:
function* logger() {
while (true) {
for (let index = 0; index < 4; index++) {
yield index
}
}
}
let generator = logger()
setInterval(() => console.log(generator.next().value), 1000)
回答2:
var counter = 0,
limit = 5,
handle; // global vars
function start() {
counter = 0;
clearInterval(handle); // reset
handle = setInterval(count, 1000); // interval handle
}
function count() {
console.log(counter++); // increment counter
if (counter >= limit) { // check limit
clearInterval(handle); // stop timer
}
}
function stop() {
clearInterval(handle);
}
start();
setTimeout(function(){
start();
},3110); // reset while counting.
As mentioned in the comments added reset functionality.
来源:https://stackoverflow.com/questions/59220387/how-to-output-each-number-consecutively-in-an-index-every-second