I need a simple way to wait for setTimeout code to finish executing and then run the code that comes after setTimeout. Now the code after loop containing setTimout is executing before loop/setTimout is finished executing.
for(let i = 0; i < 5; i++) {
setTimeout(function(){
console.log(i);
}, i*1000);
}
console.log("loop/timeout is done executing");
setTimeout
is by definition not synchronous - whatever you use to solve the issue will have to be asynchronous, there's no way around that.
The best way to achieve something like this is to use Promise
s instead, calling Promise.all
on an array of the created promises:
(async () => {
await Promise.all(Array.from(
{ length: 5 },
(_, i) => new Promise(res => setTimeout(() => {
console.log(i);
res();
}, i * 1000))
));
console.log("loop/timeout is done executing");
})();
I have a ul with items coming from the loop, and then extra li after that. <ul> <todo-item v-for="(todo,index) in todos" v-bind:todo="todo" :key="index" /> <li :key='"new_item"'>...
I have a ul with items coming from the loop, and then extra li after that. <ul> <todo-item v-for="(todo,index) in todos" v-bind:todo="todo" :key="index" /> <li :key='"new_item"'>...
I have a select tag with 4 options. I want to get a particular option clicked when the page loads and a method should called because of click event. Here what I have tried so far: HTML <select>...
I have a select tag with 4 options. I want to get a particular option clicked when the page loads and a method should called because of click event. Here what I have tried so far: HTML <select>...
I created my own method which basically capitalizes the first alphabet of every word in a string. However, I am getting this Uncaught TypeError: Cannot read property 'split' of undefined error. Where ...
I created my own method which basically capitalizes the first alphabet of every word in a string. However, I am getting this Uncaught TypeError: Cannot read property 'split' of undefined error. Where ...
I have a submit button, now I want result like this: When I click on first time it will be run action 1. When I click on second time it will be run action 2. When I click on n time it will be run ...
I have a submit button, now I want result like this: When I click on first time it will be run action 1. When I click on second time it will be run action 2. When I click on n time it will be run ...