The outer interval should be 2 seconds.
How to run one statement after another in a procedural manner in Javascript?
-
24-06-2022 - |
Question
Lets say we have a simple scenario where I would like to repeatedly output "Hello" followed by "World" 1 second later. I have tried the following:
setInterval(
function() {
console.log("Hello");
setTimeout(
function() {
console.log("World");
},
1000
);
},
1000
);
But it doesn't work, at the second interation of setInterval
the console.log
outputs Hello World at the same time.
What did I do wrong?
Solution
OTHER TIPS
This is not a direct answer to your question but I think its useful in your situation,
I created a queue runner
function that takes a list of functions to run after a period of time
Features:
- You can add as many as you want functions to the queue
- You can set if you want to run the queue once or to repeat the sequence
- Using only the
setInterval
function and without thesetTimeout
Definition:
var queue = function ( /* Array<function> */ fn, /* int */ timeout, /* boolean */ repeat) {
return function () {
var i = 0,
f = fn[i],
t = setInterval(function () {
f();
if (fn[i + 1] !== undefined) {
f = fn[++i];
} else {
if (repeat) {
i = 0;
f = fn[i];
} else {
clearInterval(t);
}
}
}, timeout);
}
}
And you call it like this :
var fn = [function(){console.log('A')}, function(){console.log('B')}];
queue(fn, 1000, true)();
JSFIDDLE:
you can check the jsfiddle Hope this help ☺
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow