Let’s say I have two arrays in my javascript:
var content = ["string1", "string2", "string3", "string4"],
milliseconds = [500, 1500, 1000, 500];
I want each element of content array to be displayed in console one by one with intervals from milliseconds array in a way that string1 is displayed after 500 milliseconds, string2 after 1500 (from the displaying of string1) and so on.
I’m a total beginner, I tried stuff like:
for (var i = 0; i < content.length - 1; i++) {
setTimeout(function() {
console.log(content[i]);
}, milliseconds[i]);
};
But it displays only the last string four times, and it looks like setTimeout methods all start at the same time, not one after another. Is there a way to get the effect I want?
First of all, the
setTimeouts all seem to start at the same time because you’re calling them at the same time. JavaScript doesn’t block – it doesn’t wait for thesetTimeoutcallback to actually fire, it just keeps going. That’s why, since you were using a loop, all of the callbacks were getting scheduled more or less at once.The second issue, that all of the
console.logs seem to print the same thing, is because of the same loop issue. Since the loop finishes way before any of the callbacks complete, the value ofiis set to the last index of the loop. Then, when the callback occurs, guess whatiis equal to?One technique would be to just keep a running index of the current item.