JavaScript : For loop with timeout
You can work that out with simple math :
for (var i=0;i<=10;i++) {
(function(ind) {
setTimeout(function(){console.log(ind);}, 1000 + (3000 * ind));
})(i);
}
1000ms : 0
4000ms : 1
7000ms : 2
10000ms : 3
13000ms : 4
...
Following the comments
It seem that your request is a bit blurry. if you want to do something after the last timeout, you can set a limit and compare the current index :var limit = 10
for (var i=0;i<=limit;i++) {
(function(ind) {
setTimeout(function(){
console.log(ind);
if(ind === limit){
console.log('It was the last one');
}
}, 1000 + (3000 * ind));
})(i);
}
Fiddle : http://jsfiddle.net/Tn4A7/I think I know what you want...
and it is to simply dofor (var i=0;i<=10;i++) {
(function(ind) {
setTimeout(function(){console.log(ind);}, 1000 * ind);
})(i);
}
For loop with setTimeout?
The simplest way is to just use a different delay in each call of setTimeout
let counter = 1
for (...){
setTimeout(function() { }, 3000 * counter++);
}
Since Object.entries returns an Array, we could also use Arrray.entries to get a iteration counter in the for statement.queries = {
"info": {
"query": "SELECT ..."
},
"info2": {
"query": "INSERT ..."
},
"infoN": {
"query": "DELETE ..."
}
}
for (let [counter, [key, value]] of Object.entries(queries).entries()) {
const delay = (counter + 1) * 1000
setTimeout(() => {
console.log({
counter,
delay,
key,
value
})
}, delay)
}
Promise inside for loop with setTimeout
Your code basically runs 10000000 api requests simultaneously after 1 second delay. You need to chain API calls so they are run after another:
const axios = require('axios');
function getData(i){
return axios.get(`http://www.api.com/${i}`);
}
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function dataLoop() {
const getOne = (i: number) => {
if (i < 10000000) {
getData(i)
.then((res) => {
console.log(`successs ${i}`);
})
.catch((err) => {
console.log(`fail ${i}`);
})
.then(wait(1000))
.then(() => getOne(i + 1))
}
}
getOne(0);
}
dataLoop();
I suggest to try using async/await if possible in your situation, it greatly simplifies things.for (let i = 0; i < 10000000; i++) {
try {
const res = await getData(i);
console.log(`successs ${i}`);
} catch (e) {
console.log(`fail ${i}`);
}
await wait(1000);
}
setTimeout executes after for loop in javascript
JS is sync. So all sync code is done first, and all async go in separate thread and they may finish earlier but they have to wait until all sync code is done.
setTimeout(function(){
console.log('setTimeout executes');
},1000); // this function go async in separate thread
for(var i=0;i<10000;i++){
console.log('inside for loop'); // sync
}
console.log('after For Loop'); // sync
// after all sync code async result will be called
// console.log('setTimeout executes'); will happen here
If you want full picture of how JS engines works read this. It is very basic and helps a lot. While loop with an async setTimeout function
Your promise in delay
/timeout
function never resolves.
Here's how it will work. Note the resolve
parameter of the promise callback.
function delay(message) {
return new Promise((resolve) => setTimeout(function () {
console.log(message);
resolve();
}, 3000))
}
(async () => {
while (true) {
console.log("Start")
await delay("No")
console.log("End")
}
})();
How do I add a delay in a JavaScript loop?
The setTimeout()
function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.
You may want to use something like this instead:
var i = 1; // set your counter to 1
function myLoop() { // create a loop function setTimeout(function() { // call a 3s setTimeout when the loop is called console.log('hello'); // your code here i++; // increment the counter if (i < 10) { // if the counter < 10, call the loop function myLoop(); // .. again which will trigger another } // .. setTimeout() }, 3000)}
myLoop(); // start the loop
Related Topics
How to Detect When a Tab Is Focused or Not in Chrome with JavaScript
How to Compare 2 Functions in JavaScript
How to Execute a Function on Pressing the Enter Key in an <Input> Field
How to Auto-Reload a Chrome Extension I'm Developing
How to Check Dimensions of Image Before Uploading
Why Does Console.Log Say Undefined, and Then the Correct Value
Executing Code at Page-Level from Background.Js and Returning the Value
Window.Location.Reload with Clear Cache
Decompress Gzip and Zlib String in JavaScript
JavaScript Loop Variable Scope
How to Build a Loop in JavaScript
Differencebetween Native Objects and Host Objects
Set Window to Fullscreen (Real Fullscreen; F11 Functionality) by JavaScript
What the Difference Between Loadcomplete and Gridcomplete Events
How to Detect If JavaScript Files Are Loaded
Does It Make Sense to Use Require.Js with Angular.Js