codyc4321
codyc4321

Reputation: 9672

setInterval usage causes strange infinite loop

I am trying a map lesson and got tripped up on setInterval causing an infinite loop. Since I am only going over a list with 5 elements, I don't understand why this is happening; it prints out all 5 numbers like:

1
2
3
4
5

over and over again forever with:

var list = [1, 2, 3, 4, 5];

function delayedPrint(text, delay = 400) {
    setInterval(function() {
        console.log(text);
    }, delay)
}

console.log('\nMap can take 1 argument, which is each item in the array:')

list.map(function(this_list_item) {
    delayedPrint(this_list_item);
});

but changing delayedPrint(this_list_item); to console.log(this_list_item); the code works as normal, printing each item 1 time.

Why does this infinite loop happen and how can I print these items with an arbitrary delay? `setInterval` Apparent Infinite Loop didn't help.

Upvotes: 0

Views: 236

Answers (2)

Damiano
Damiano

Reputation: 811

You have to use setTimeout to call a function once with a delay.

setInterval will call that function an unlimited number of times every delay milliseconds.

If what you are trying to achieve is printing an item, then another after delay milliseconds, and so on, this is a way to achieve it (manually incrementing the delay for each item):

var list = [1, 2, 3, 4, 5];
var delay = 400;

function delayedPrint(text, delay = 1000) {
    setTimeout(function() {
        console.log(text);
    }, delay)
}

list.map(function(this_list_item, index) {
    delayedPrint(this_list_item, index * delay);
});

By the way, as Nina correctly points out, map may not be the best choice to convey what you are doing here, and forEach would be clearer:

list.forEach(function(this_list_item, index) {
    delayedPrint(this_list_item, index * delay);
});

Upvotes: 1

str
str

Reputation: 44969

That is what setInterval is supposed to do:

The setInterval() method of the WindowOrWorkerGlobalScope mixin repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

What you want, however, is setTimeout.

Upvotes: 1

Related Questions