How do I Sum Array elements in every second - javascript

I'm trying to sum up the array of elements by every seconds. My array has 20 elements, and it should be summed up in 20seconds.
I'm using setTimeout in for loop but its not working , the loop finish before the first second. Anyway to achieve ?
for (var o = 0; o < 20; o++) {
setTimeout(function () {
tempPsum += array[o];
}, 1000);
}

Right, the loop finishes before the first setTimeout callback occurs. Your code schedules 20 callbacks that all occur, one after another, a second later.
You have two choices:
Schedule each one a second later than the previous one, or
Don't schedule the next one until the previous one finishes
#1 is simpler, so let's do that:
for (let o = 0; o < 20; o++) {
// ^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
setTimeout(function () {
tempPsum += array[o];
}, 1000 * o);
// ^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−
}
By multiplying the delay time by o, we get 0 for the first timer, 1000 for the second, 3000 for the third...
Note the change from var to let. That way, there's a separate o for the callback to close over for each loop iteration. (See answers here, or...Chapter 2 of my new book. :-) )
If you can't use ES2015+ features in your environment, you can use the extra arguments to setTimeout instead:
for (var o = 0; o < 20; o++) {
setTimeout(function (index) {
// ^^^^^−−−−−−−−−−−
tempPsum += array[index];
// ^^^^^−−−−−−−−−−−
}, 1000 * o, o);
// ^^^^−−^−−−−−−−−−−−−−−−−−−−−−−−
}
That tells setTimeout to pass the third argument you give it to the callback as its first argument.

Ideal use case of setTimeout() is when you have to perform an operation once after a specific time frame. The scenario mentioned above requires same operation that is adding array element after a fixed time frame, so I believe setInterval() would be a better option.
var array = [1,2,3,4,5];
var tempSum = 0, i = 0;
var intrvl = setInterval( ()=> {
tempSum += array[i++];
console.log(tempSum)
if(i === array.length)
clearInterval(intrvl)
}, 1000)

This answer doesn't explain what the issue is, but offers an alternative to the other solutions. Instead of modifying the timeout using the index, you could add a sleep function that resolves a promise in a given amount of time.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
Then loop through your array using for...of and sleep each iteration for a given amount of time.
let sum = 0;
for (const number of numbers) {
await sleep(1000);
sum += number;
}
This does require the code to be placed in an async function.
const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const numbers = Array.from({length: 20}, () => randomInt(10, 99));
console.log("numbers =", ...numbers);
(async () => {
let sum = 0;
for (const number of numbers) {
await sleep(1000);
console.log(sum, "+", number, "=", sum += number);
}
})();

#TJCrowder has said why your version doesn't work.
I will suggest another solution:
Another way: use setInterval
let numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
let tempPsum = 0
let i = 0
let intervalId = setInterval(function () {
tempPsum += numbers[i];
i = i + 1;
console.log(tempPsum);
if (i == 20) {clearInterval(intervalId)}
}, 1000);

I think you can use this approach:
var i = 0;
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var sum = 0;
function myLoop() {
setTimeout(() => {
sum = sum + arr[i];
console.log(sum);
i++;
if (i < 20) {
myLoop();
}
}, 1000)
}
myLoop();

Related

For a setTimeout in a for loop, why is necessary to multiply the iterating value(i) to the timer, and upon multiplying its not working as expected [duplicate]

I would like to add a delay/sleep inside a while loop:
I tried it like this:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}
Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.
What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.
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
You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:
(function myLoop(i) {
setTimeout(function() {
console.log('hello'); // your code here
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10); // pass the number of iterations as an argument
Since ES7 theres a better way to await a loop:
// Returns a Promise that resolves after "ms" Milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))
async function load () { // We need to wrap the loop into an async function for this to work
for (var i = 0; i < 3; i++) {
console.log(i);
await timer(3000); // then the created Promise can be awaited
}
}
load();
When the engine reaches the await part, it sets a timeout and halts the execution of the async function. Then when the timeout completes, execution continues at that point. That's quite useful as you can delay (1) nested loops, (2) conditionally, (3) nested functions:
async function task(i) { // 3
await timer(1000);
console.log(`Task ${i} done!`);
}
async function main() {
for(let i = 0; i < 100; i+= 10) {
for(let j = 0; j < 10; j++) { // 1
if(j % 2) { // 2
await task(i + j);
}
}
}
}
main();
function timer(ms) { return new Promise(res => setTimeout(res, ms)); }
Reference on MDN
While ES7 is now supported by NodeJS and modern browsers, you might want to transpile it with BabelJS so that it runs everywhere.
If using ES6, you could use a for loop to achieve this:
for (let i = 1; i < 10; i++) {
setTimeout(function timer() {
console.log("hello world");
}, i * 3000);
}
It declares i for each iteration, meaning the timeout is what it was before + 1000. This way, what is passed to setTimeout is exactly what we want.
Try something like this:
var i = 0, howManyTimes = 10;
function f() {
console.log("hi");
i++;
if (i < howManyTimes) {
setTimeout(f, 3000);
}
}
f();
Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.
for (var start = 1; start < 10; start++)
setTimeout(function () { alert('hello'); }, 3000 * start);
The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.
This will work
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() { console.log(i); }, 100 * i);
})(i);
}
Try this fiddle: https://jsfiddle.net/wgdx8zqq/
I think you need something like this:
var TimedQueue = function(defaultDelay){
this.queue = [];
this.index = 0;
this.defaultDelay = defaultDelay || 3000;
};
TimedQueue.prototype = {
add: function(fn, delay){
this.queue.push({
fn: fn,
delay: delay
});
},
run: function(index){
(index || index === 0) && (this.index = index);
this.next();
},
next: function(){
var self = this
, i = this.index++
, at = this.queue[i]
, next = this.queue[this.index]
if(!at) return;
at.fn();
next && setTimeout(function(){
self.next();
}, next.delay||this.defaultDelay);
},
reset: function(){
this.index = 0;
}
}
Test code:
var now = +new Date();
var x = new TimedQueue(2000);
x.add(function(){
console.log('hey');
console.log(+new Date() - now);
});
x.add(function(){
console.log('ho');
console.log(+new Date() - now);
}, 3000);
x.add(function(){
console.log('bye');
console.log(+new Date() - now);
});
x.run();
Note: using alerts stalls javascript execution till you close the alert.
It might be more code than you asked for, but this is a robust reusable solution.
You can create a sleep function that promisifies setTimeout. This enables you to use async/await to write code without callbacks and the familiar for loop control flow.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
for (let i = 0; i < 10; i++) {
console.log(i);
await sleep(1000);
}
console.log("done");
})();
In Node, you can use timers/promises to avoid the promisification step (if the feature isn't supported on your older Node version, the above code works just as well):
const {setTimeout: sleep} = require("timers/promises");
// same code as above
Regardless, since JS is single-threaded, it's a good thing that timeouts are asynchronous. If they weren't, the browser wouldn't get a chance to repaint the UI, leading to a frozen interface for the user.
I would probably use setInterval, like this:
var period = 1000; // ms
var endTime = 10000; // ms
var counter = 0;
var sleepyAlert = setInterval(function(){
alert('Hello');
if(counter === endTime){
clearInterval(sleepyAlert);
}
counter += period;
}, period);
In my opinion, the simpler and most elegant way to add a delay in a loop is like this:
names = ['John', 'Ana', 'Mary'];
names.forEach((name, i) => {
setTimeout(() => {
console.log(name);
}, i * 1000); // one sec interval
});
In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.
Generators, a new feature of ECMAScript 6, are functions that can be
paused and resumed. Calling genFunc does not execute it. Instead, it
returns a so-called generator object that lets us control genFunc’s
execution. genFunc() is initially suspended at the beginning of its
body. The method genObj.next() continues the execution of genFunc,
until the next yield.
(Exploring ES6)
Code example:
let arr = [1, 2, 3, 'b'];
let genObj = genFunc();
let val = genObj.next();
console.log(val.value);
let interval = setInterval(() => {
val = genObj.next();
if (val.done) {
clearInterval(interval);
} else {
console.log(val.value);
}
}, 1000);
function* genFunc() {
for(let item of arr) {
yield item;
}
}
So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).
I do this with Bluebird’s Promise.delay and recursion.
function myLoop(i) {
return Promise.delay(1000)
.then(function() {
if (i > 0) {
alert('hello');
return myLoop(i -= 1);
}
});
}
myLoop(3);
<script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>
Dead-simple, one-line solution with an actual async-await delay (no queued setTimeout):
The following (self-executing anonymous) function creates an actual delay between loops, instead of multiple setTimeouts with different timeouts, which might mess up memory.
In each of the 100 loops, it awaits for a new Promise to resolve.
This happens only after setTimeout 'allows' it after 90ms. Until then, code is blocked by the async-await / pending Promise.
(async () => {
for (let i=0; i<100; i++) {
await new Promise((resolve) => {setTimeout(() => {document.write(`${i} `); resolve(true)}, 90)});
}
})()
In ES6 you can do as following:
for (let i = 0; i <= 10; i++){
setTimeout(function () {
console.log(i);
}, i*3000)
}
In ES5 you can do as:
for (var i = 0; i <= 10; i++){
(function(i) {
setTimeout(function () {
console.log(i);
}, i*3000)
})(i);
}
The reason is, let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
A function-less solution
I am a bit late to the party, but there is a solution without using any functions:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(() => alert('hello'), 3000 * start);
}
Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:
function timeout(range, time, callback){
var i = range[0];
callback(i);
Loop();
function Loop(){
setTimeout(function(){
i++;
if (i<range[1]){
callback(i);
Loop();
}
}, time*1000)
}
}
For example:
//This function prints the loop number every second
timeout([0, 5], 1, function(i){
console.log(i);
});
Would be equivalent to:
//This function prints the loop number instantly
for (var i = 0; i<5; i++){
console.log(i);
}
To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:
var looper = async function () {
for (var start = 1; start < 10; start++) {
await new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("iteration: " + start.toString());
resolve(true);
}, 1000);
});
}
return true;
}
And then you call run it like so:
looper().then(function(){
console.log("DONE!")
});
Please take some time to get a good understanding of asynchronous programming.
In addition to the accepted answer from 10 years ago, with more modern Javascript one can use async/await/Promise() or generator function to achieve the correct behavior. (The incorrect behavior suggested in other answers would be setting series of 3 seconds alerts regardless of "accepting" the alert() - or finishing the task at hand)
Using async/await/Promise():
alert('hi');
(async () => {
for(let start = 1; start < 10; start++) {
await new Promise(resolve => setTimeout(() => {
alert('hello');
resolve();
}, 3000));
}
})();
Using a generator function:
alert('hi');
let func;
(func = (function*() {
for(let start = 1; start < 10; start++) {
yield setTimeout(() => {
alert('hello');
func.next();
}, 3000);
}
})()).next();
You can use the RxJS interval operator. interval emits an integer every x seconds, and take specifies the number of times it emits these numbers.
Rx.Observable
.interval(1000)
.take(10)
.subscribe((x) => console.log(x))
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 1000;
function functionToRun(i, length) {
alert(data[i]);
}
(function forWithDelay(i, length, fn, delay) {
setTimeout(function() {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:
First let's define some essential variables:
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 3000;
Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:
function functionToRun(i, length) {
alert(data[i]);
}
Self-executing version
(function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
Functional version
function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
}
forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it
Just try this
var arr = ['A','B','C'];
(function customLoop (arr, i) {
setTimeout(function () {
// Do here what you want to do.......
console.log(arr[i]);
if (--i) {
customLoop(arr, i);
}
}, 2000);
})(arr, arr.length);
Result
A // after 2s
B // after 2s
C // after 2s
This script works for most things
function timer(start) {
setTimeout(function () { //The timer
alert('hello');
}, start*3000); //needs the "start*" or else all the timers will run at 3000ms
}
for(var start = 1; start < 10; start++) {
timer(start);
}
Here is how I created an infinite loop with a delay that breaks on a certain condition:
// Now continuously check the app status until it's completed,
// failed or times out. The isFinished() will throw exception if
// there is a failure.
while (true) {
let status = await this.api.getStatus(appId);
if (isFinished(status)) {
break;
} else {
// Delay before running the next loop iteration:
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
The key here is to create a new Promise that resolves by timeout, and to await for its resolution.
Obviously you need async/await support for that. Works in Node 8.
for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).
function iAsk(lvl){
var i=0;
var intr =setInterval(function(){ // start the loop
i++; // increment it
if(i>lvl){ // check if the end round reached.
clearInterval(intr);
return;
}
setTimeout(function(){
$(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
},50);
setTimeout(function(){
// do another bla bla bla after 100 millisecond.
seq[i-1]=(Math.ceil(Math.random()*4)).toString();
$("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
$("#d"+seq[i-1]).prop("src",pGif);
var d =document.getElementById('aud');
d.play();
},100);
setTimeout(function(){
// keep adding bla bla bla till you done :)
$("#d"+seq[i-1]).prop("src",pPng);
},900);
},1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
}
PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.
PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..
let counter =1;
for(let item in items) {
counter++;
setTimeout(()=>{
//your code
},counter*5000); //5Sec delay between each iteration
}
const autoPlayer = (arr = [1, 2, 3, 4, 5]) => {
// Base case:
if (arr.length < 1) return
// Remove the first element from the array.
const item = arr.shift()
// Set timout
setTimeout(() => {
console.log('Hello, world!', item) // Visualisation.
autoPlayer() // Call function again.
}, 1000) // Iterate every second.
}
Hey, I know this post is very old, but this code "loops" and adds a delay to it using a recursive method. I don't think you can 'actually' delay a loop itself from iterating based on reading various comments from other people. Maybe this can help someone out! Basically the function accepts an array (in this example). On each iteration the setTimeout Javascript method is called. The function calls itself again indefinitely when the timer of the setTimeout function expires, but on each call the array becomes smaller until it reaches the base-case. I hope this can help anyone else out.
/*
Use Recursive and setTimeout
call below function will run loop loopFunctionNeedCheck until
conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
reRunAfterMs miliseconds and continue loop
tested code, thanks
*/
function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
loopFunctionNeedCheck) {
loopFunctionNeedCheck();
var result = conditionCheckAfterRunFn();
//check after run
if (!result) {
setTimeout(function () {
functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
}, reRunAfterMs);
}
else console.log("completed, thanks");
//if you need call a function after completed add code call callback in here
}
//passing-parameters-to-a-callback-function
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
//test code:
var result = 0;
console.log("---> init result is " + result);
var functionNeedRun = function (step) {
result+=step;
console.log("current result is " + result);
}
var checkResultFunction = function () {
return result==100;
}
//call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));
//result log from console:
/*
---> init result is 0
current result is 5
undefined
current result is 10
current result is 15
current result is 20
current result is 25
current result is 30
current result is 35
current result is 40
current result is 45
current result is 50
current result is 55
current result is 60
current result is 65
current result is 70
current result is 75
current result is 80
current result is 85
current result is 90
current result is 95
current result is 100
completed, thanks
*/
Here is a function that I use for looping over an array:
function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){
if (i < theArray.length && typeof delayAmount == 'number'){
console.log("i "+i);
theFunction(theArray[i], i);
setTimeout(function(){
loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
}else{
onComplete(i);
}
}
You use it like this:
loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
//Do something with item
}, function(i){
//Do something once loop has completed
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
for(var i=0; i<5; i++) {
var sno = i+1;
(function myLoop (i) {
setTimeout(function () {
alert(i); // Do your function here
}, 1000*i);
})(sno);
}
}
</script>
</body>
</html>
Try this...
var icount=0;
for (let i in items) {
icount=icount+1000;
new beginCount(items[i],icount);
}
function beginCount(item,icount){
setTimeout(function () {
new actualFunction(item,icount);
}, icount);
}
function actualFunction(item,icount){
//...runs ever 1 second
console.log(icount);
}

setTimeout in nested for loops in JavaScript not working like what I want [duplicate]

I would like to add a delay/sleep inside a while loop:
I tried it like this:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}
Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.
What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.
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
You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:
(function myLoop(i) {
setTimeout(function() {
console.log('hello'); // your code here
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10); // pass the number of iterations as an argument
Since ES7 theres a better way to await a loop:
// Returns a Promise that resolves after "ms" Milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))
async function load () { // We need to wrap the loop into an async function for this to work
for (var i = 0; i < 3; i++) {
console.log(i);
await timer(3000); // then the created Promise can be awaited
}
}
load();
When the engine reaches the await part, it sets a timeout and halts the execution of the async function. Then when the timeout completes, execution continues at that point. That's quite useful as you can delay (1) nested loops, (2) conditionally, (3) nested functions:
async function task(i) { // 3
await timer(1000);
console.log(`Task ${i} done!`);
}
async function main() {
for(let i = 0; i < 100; i+= 10) {
for(let j = 0; j < 10; j++) { // 1
if(j % 2) { // 2
await task(i + j);
}
}
}
}
main();
function timer(ms) { return new Promise(res => setTimeout(res, ms)); }
Reference on MDN
While ES7 is now supported by NodeJS and modern browsers, you might want to transpile it with BabelJS so that it runs everywhere.
If using ES6, you could use a for loop to achieve this:
for (let i = 1; i < 10; i++) {
setTimeout(function timer() {
console.log("hello world");
}, i * 3000);
}
It declares i for each iteration, meaning the timeout is what it was before + 1000. This way, what is passed to setTimeout is exactly what we want.
Try something like this:
var i = 0, howManyTimes = 10;
function f() {
console.log("hi");
i++;
if (i < howManyTimes) {
setTimeout(f, 3000);
}
}
f();
Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.
for (var start = 1; start < 10; start++)
setTimeout(function () { alert('hello'); }, 3000 * start);
The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.
This will work
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() { console.log(i); }, 100 * i);
})(i);
}
Try this fiddle: https://jsfiddle.net/wgdx8zqq/
I think you need something like this:
var TimedQueue = function(defaultDelay){
this.queue = [];
this.index = 0;
this.defaultDelay = defaultDelay || 3000;
};
TimedQueue.prototype = {
add: function(fn, delay){
this.queue.push({
fn: fn,
delay: delay
});
},
run: function(index){
(index || index === 0) && (this.index = index);
this.next();
},
next: function(){
var self = this
, i = this.index++
, at = this.queue[i]
, next = this.queue[this.index]
if(!at) return;
at.fn();
next && setTimeout(function(){
self.next();
}, next.delay||this.defaultDelay);
},
reset: function(){
this.index = 0;
}
}
Test code:
var now = +new Date();
var x = new TimedQueue(2000);
x.add(function(){
console.log('hey');
console.log(+new Date() - now);
});
x.add(function(){
console.log('ho');
console.log(+new Date() - now);
}, 3000);
x.add(function(){
console.log('bye');
console.log(+new Date() - now);
});
x.run();
Note: using alerts stalls javascript execution till you close the alert.
It might be more code than you asked for, but this is a robust reusable solution.
You can create a sleep function that promisifies setTimeout. This enables you to use async/await to write code without callbacks and the familiar for loop control flow.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
for (let i = 0; i < 10; i++) {
console.log(i);
await sleep(1000);
}
console.log("done");
})();
In Node, you can use timers/promises to avoid the promisification step (if the feature isn't supported on your older Node version, the above code works just as well):
const {setTimeout: sleep} = require("timers/promises");
// same code as above
Regardless, since JS is single-threaded, it's a good thing that timeouts are asynchronous. If they weren't, the browser wouldn't get a chance to repaint the UI, leading to a frozen interface for the user.
I would probably use setInterval, like this:
var period = 1000; // ms
var endTime = 10000; // ms
var counter = 0;
var sleepyAlert = setInterval(function(){
alert('Hello');
if(counter === endTime){
clearInterval(sleepyAlert);
}
counter += period;
}, period);
In my opinion, the simpler and most elegant way to add a delay in a loop is like this:
names = ['John', 'Ana', 'Mary'];
names.forEach((name, i) => {
setTimeout(() => {
console.log(name);
}, i * 1000); // one sec interval
});
In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.
Generators, a new feature of ECMAScript 6, are functions that can be
paused and resumed. Calling genFunc does not execute it. Instead, it
returns a so-called generator object that lets us control genFunc’s
execution. genFunc() is initially suspended at the beginning of its
body. The method genObj.next() continues the execution of genFunc,
until the next yield.
(Exploring ES6)
Code example:
let arr = [1, 2, 3, 'b'];
let genObj = genFunc();
let val = genObj.next();
console.log(val.value);
let interval = setInterval(() => {
val = genObj.next();
if (val.done) {
clearInterval(interval);
} else {
console.log(val.value);
}
}, 1000);
function* genFunc() {
for(let item of arr) {
yield item;
}
}
So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).
I do this with Bluebird’s Promise.delay and recursion.
function myLoop(i) {
return Promise.delay(1000)
.then(function() {
if (i > 0) {
alert('hello');
return myLoop(i -= 1);
}
});
}
myLoop(3);
<script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>
Dead-simple, one-line solution with an actual async-await delay (no queued setTimeout):
The following (self-executing anonymous) function creates an actual delay between loops, instead of multiple setTimeouts with different timeouts, which might mess up memory.
In each of the 100 loops, it awaits for a new Promise to resolve.
This happens only after setTimeout 'allows' it after 90ms. Until then, code is blocked by the async-await / pending Promise.
(async () => {
for (let i=0; i<100; i++) {
await new Promise((resolve) => {setTimeout(() => {document.write(`${i} `); resolve(true)}, 90)});
}
})()
In ES6 you can do as following:
for (let i = 0; i <= 10; i++){
setTimeout(function () {
console.log(i);
}, i*3000)
}
In ES5 you can do as:
for (var i = 0; i <= 10; i++){
(function(i) {
setTimeout(function () {
console.log(i);
}, i*3000)
})(i);
}
The reason is, let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
A function-less solution
I am a bit late to the party, but there is a solution without using any functions:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(() => alert('hello'), 3000 * start);
}
Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:
function timeout(range, time, callback){
var i = range[0];
callback(i);
Loop();
function Loop(){
setTimeout(function(){
i++;
if (i<range[1]){
callback(i);
Loop();
}
}, time*1000)
}
}
For example:
//This function prints the loop number every second
timeout([0, 5], 1, function(i){
console.log(i);
});
Would be equivalent to:
//This function prints the loop number instantly
for (var i = 0; i<5; i++){
console.log(i);
}
To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:
var looper = async function () {
for (var start = 1; start < 10; start++) {
await new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("iteration: " + start.toString());
resolve(true);
}, 1000);
});
}
return true;
}
And then you call run it like so:
looper().then(function(){
console.log("DONE!")
});
Please take some time to get a good understanding of asynchronous programming.
In addition to the accepted answer from 10 years ago, with more modern Javascript one can use async/await/Promise() or generator function to achieve the correct behavior. (The incorrect behavior suggested in other answers would be setting series of 3 seconds alerts regardless of "accepting" the alert() - or finishing the task at hand)
Using async/await/Promise():
alert('hi');
(async () => {
for(let start = 1; start < 10; start++) {
await new Promise(resolve => setTimeout(() => {
alert('hello');
resolve();
}, 3000));
}
})();
Using a generator function:
alert('hi');
let func;
(func = (function*() {
for(let start = 1; start < 10; start++) {
yield setTimeout(() => {
alert('hello');
func.next();
}, 3000);
}
})()).next();
You can use the RxJS interval operator. interval emits an integer every x seconds, and take specifies the number of times it emits these numbers.
Rx.Observable
.interval(1000)
.take(10)
.subscribe((x) => console.log(x))
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 1000;
function functionToRun(i, length) {
alert(data[i]);
}
(function forWithDelay(i, length, fn, delay) {
setTimeout(function() {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:
First let's define some essential variables:
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 3000;
Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:
function functionToRun(i, length) {
alert(data[i]);
}
Self-executing version
(function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
Functional version
function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
}
forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it
Just try this
var arr = ['A','B','C'];
(function customLoop (arr, i) {
setTimeout(function () {
// Do here what you want to do.......
console.log(arr[i]);
if (--i) {
customLoop(arr, i);
}
}, 2000);
})(arr, arr.length);
Result
A // after 2s
B // after 2s
C // after 2s
This script works for most things
function timer(start) {
setTimeout(function () { //The timer
alert('hello');
}, start*3000); //needs the "start*" or else all the timers will run at 3000ms
}
for(var start = 1; start < 10; start++) {
timer(start);
}
Here is how I created an infinite loop with a delay that breaks on a certain condition:
// Now continuously check the app status until it's completed,
// failed or times out. The isFinished() will throw exception if
// there is a failure.
while (true) {
let status = await this.api.getStatus(appId);
if (isFinished(status)) {
break;
} else {
// Delay before running the next loop iteration:
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
The key here is to create a new Promise that resolves by timeout, and to await for its resolution.
Obviously you need async/await support for that. Works in Node 8.
for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).
function iAsk(lvl){
var i=0;
var intr =setInterval(function(){ // start the loop
i++; // increment it
if(i>lvl){ // check if the end round reached.
clearInterval(intr);
return;
}
setTimeout(function(){
$(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
},50);
setTimeout(function(){
// do another bla bla bla after 100 millisecond.
seq[i-1]=(Math.ceil(Math.random()*4)).toString();
$("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
$("#d"+seq[i-1]).prop("src",pGif);
var d =document.getElementById('aud');
d.play();
},100);
setTimeout(function(){
// keep adding bla bla bla till you done :)
$("#d"+seq[i-1]).prop("src",pPng);
},900);
},1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
}
PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.
PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..
let counter =1;
for(let item in items) {
counter++;
setTimeout(()=>{
//your code
},counter*5000); //5Sec delay between each iteration
}
const autoPlayer = (arr = [1, 2, 3, 4, 5]) => {
// Base case:
if (arr.length < 1) return
// Remove the first element from the array.
const item = arr.shift()
// Set timout
setTimeout(() => {
console.log('Hello, world!', item) // Visualisation.
autoPlayer() // Call function again.
}, 1000) // Iterate every second.
}
Hey, I know this post is very old, but this code "loops" and adds a delay to it using a recursive method. I don't think you can 'actually' delay a loop itself from iterating based on reading various comments from other people. Maybe this can help someone out! Basically the function accepts an array (in this example). On each iteration the setTimeout Javascript method is called. The function calls itself again indefinitely when the timer of the setTimeout function expires, but on each call the array becomes smaller until it reaches the base-case. I hope this can help anyone else out.
/*
Use Recursive and setTimeout
call below function will run loop loopFunctionNeedCheck until
conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
reRunAfterMs miliseconds and continue loop
tested code, thanks
*/
function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
loopFunctionNeedCheck) {
loopFunctionNeedCheck();
var result = conditionCheckAfterRunFn();
//check after run
if (!result) {
setTimeout(function () {
functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
}, reRunAfterMs);
}
else console.log("completed, thanks");
//if you need call a function after completed add code call callback in here
}
//passing-parameters-to-a-callback-function
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
//test code:
var result = 0;
console.log("---> init result is " + result);
var functionNeedRun = function (step) {
result+=step;
console.log("current result is " + result);
}
var checkResultFunction = function () {
return result==100;
}
//call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));
//result log from console:
/*
---> init result is 0
current result is 5
undefined
current result is 10
current result is 15
current result is 20
current result is 25
current result is 30
current result is 35
current result is 40
current result is 45
current result is 50
current result is 55
current result is 60
current result is 65
current result is 70
current result is 75
current result is 80
current result is 85
current result is 90
current result is 95
current result is 100
completed, thanks
*/
Here is a function that I use for looping over an array:
function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){
if (i < theArray.length && typeof delayAmount == 'number'){
console.log("i "+i);
theFunction(theArray[i], i);
setTimeout(function(){
loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
}else{
onComplete(i);
}
}
You use it like this:
loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
//Do something with item
}, function(i){
//Do something once loop has completed
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
for(var i=0; i<5; i++) {
var sno = i+1;
(function myLoop (i) {
setTimeout(function () {
alert(i); // Do your function here
}, 1000*i);
})(sno);
}
}
</script>
</body>
</html>
Try this...
var icount=0;
for (let i in items) {
icount=icount+1000;
new beginCount(items[i],icount);
}
function beginCount(item,icount){
setTimeout(function () {
new actualFunction(item,icount);
}, icount);
}
function actualFunction(item,icount){
//...runs ever 1 second
console.log(icount);
}

Javascript Fetch Api Data and show each item [duplicate]

I would like to add a delay/sleep inside a while loop:
I tried it like this:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}
Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.
What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.
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
You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:
(function myLoop(i) {
setTimeout(function() {
console.log('hello'); // your code here
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10); // pass the number of iterations as an argument
Since ES7 theres a better way to await a loop:
// Returns a Promise that resolves after "ms" Milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))
async function load () { // We need to wrap the loop into an async function for this to work
for (var i = 0; i < 3; i++) {
console.log(i);
await timer(3000); // then the created Promise can be awaited
}
}
load();
When the engine reaches the await part, it sets a timeout and halts the execution of the async function. Then when the timeout completes, execution continues at that point. That's quite useful as you can delay (1) nested loops, (2) conditionally, (3) nested functions:
async function task(i) { // 3
await timer(1000);
console.log(`Task ${i} done!`);
}
async function main() {
for(let i = 0; i < 100; i+= 10) {
for(let j = 0; j < 10; j++) { // 1
if(j % 2) { // 2
await task(i + j);
}
}
}
}
main();
function timer(ms) { return new Promise(res => setTimeout(res, ms)); }
Reference on MDN
While ES7 is now supported by NodeJS and modern browsers, you might want to transpile it with BabelJS so that it runs everywhere.
If using ES6, you could use a for loop to achieve this:
for (let i = 1; i < 10; i++) {
setTimeout(function timer() {
console.log("hello world");
}, i * 3000);
}
It declares i for each iteration, meaning the timeout is what it was before + 1000. This way, what is passed to setTimeout is exactly what we want.
Try something like this:
var i = 0, howManyTimes = 10;
function f() {
console.log("hi");
i++;
if (i < howManyTimes) {
setTimeout(f, 3000);
}
}
f();
Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.
for (var start = 1; start < 10; start++)
setTimeout(function () { alert('hello'); }, 3000 * start);
The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.
This will work
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() { console.log(i); }, 100 * i);
})(i);
}
Try this fiddle: https://jsfiddle.net/wgdx8zqq/
I think you need something like this:
var TimedQueue = function(defaultDelay){
this.queue = [];
this.index = 0;
this.defaultDelay = defaultDelay || 3000;
};
TimedQueue.prototype = {
add: function(fn, delay){
this.queue.push({
fn: fn,
delay: delay
});
},
run: function(index){
(index || index === 0) && (this.index = index);
this.next();
},
next: function(){
var self = this
, i = this.index++
, at = this.queue[i]
, next = this.queue[this.index]
if(!at) return;
at.fn();
next && setTimeout(function(){
self.next();
}, next.delay||this.defaultDelay);
},
reset: function(){
this.index = 0;
}
}
Test code:
var now = +new Date();
var x = new TimedQueue(2000);
x.add(function(){
console.log('hey');
console.log(+new Date() - now);
});
x.add(function(){
console.log('ho');
console.log(+new Date() - now);
}, 3000);
x.add(function(){
console.log('bye');
console.log(+new Date() - now);
});
x.run();
Note: using alerts stalls javascript execution till you close the alert.
It might be more code than you asked for, but this is a robust reusable solution.
You can create a sleep function that promisifies setTimeout. This enables you to use async/await to write code without callbacks and the familiar for loop control flow.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
for (let i = 0; i < 10; i++) {
console.log(i);
await sleep(1000);
}
console.log("done");
})();
In Node, you can use timers/promises to avoid the promisification step (if the feature isn't supported on your older Node version, the above code works just as well):
const {setTimeout: sleep} = require("timers/promises");
// same code as above
Regardless, since JS is single-threaded, it's a good thing that timeouts are asynchronous. If they weren't, the browser wouldn't get a chance to repaint the UI, leading to a frozen interface for the user.
I would probably use setInterval, like this:
var period = 1000; // ms
var endTime = 10000; // ms
var counter = 0;
var sleepyAlert = setInterval(function(){
alert('Hello');
if(counter === endTime){
clearInterval(sleepyAlert);
}
counter += period;
}, period);
In my opinion, the simpler and most elegant way to add a delay in a loop is like this:
names = ['John', 'Ana', 'Mary'];
names.forEach((name, i) => {
setTimeout(() => {
console.log(name);
}, i * 1000); // one sec interval
});
In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.
Generators, a new feature of ECMAScript 6, are functions that can be
paused and resumed. Calling genFunc does not execute it. Instead, it
returns a so-called generator object that lets us control genFunc’s
execution. genFunc() is initially suspended at the beginning of its
body. The method genObj.next() continues the execution of genFunc,
until the next yield.
(Exploring ES6)
Code example:
let arr = [1, 2, 3, 'b'];
let genObj = genFunc();
let val = genObj.next();
console.log(val.value);
let interval = setInterval(() => {
val = genObj.next();
if (val.done) {
clearInterval(interval);
} else {
console.log(val.value);
}
}, 1000);
function* genFunc() {
for(let item of arr) {
yield item;
}
}
So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).
I do this with Bluebird’s Promise.delay and recursion.
function myLoop(i) {
return Promise.delay(1000)
.then(function() {
if (i > 0) {
alert('hello');
return myLoop(i -= 1);
}
});
}
myLoop(3);
<script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>
Dead-simple, one-line solution with an actual async-await delay (no queued setTimeout):
The following (self-executing anonymous) function creates an actual delay between loops, instead of multiple setTimeouts with different timeouts, which might mess up memory.
In each of the 100 loops, it awaits for a new Promise to resolve.
This happens only after setTimeout 'allows' it after 90ms. Until then, code is blocked by the async-await / pending Promise.
(async () => {
for (let i=0; i<100; i++) {
await new Promise((resolve) => {setTimeout(() => {document.write(`${i} `); resolve(true)}, 90)});
}
})()
In ES6 you can do as following:
for (let i = 0; i <= 10; i++){
setTimeout(function () {
console.log(i);
}, i*3000)
}
In ES5 you can do as:
for (var i = 0; i <= 10; i++){
(function(i) {
setTimeout(function () {
console.log(i);
}, i*3000)
})(i);
}
The reason is, let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
A function-less solution
I am a bit late to the party, but there is a solution without using any functions:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(() => alert('hello'), 3000 * start);
}
Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:
function timeout(range, time, callback){
var i = range[0];
callback(i);
Loop();
function Loop(){
setTimeout(function(){
i++;
if (i<range[1]){
callback(i);
Loop();
}
}, time*1000)
}
}
For example:
//This function prints the loop number every second
timeout([0, 5], 1, function(i){
console.log(i);
});
Would be equivalent to:
//This function prints the loop number instantly
for (var i = 0; i<5; i++){
console.log(i);
}
To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:
var looper = async function () {
for (var start = 1; start < 10; start++) {
await new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("iteration: " + start.toString());
resolve(true);
}, 1000);
});
}
return true;
}
And then you call run it like so:
looper().then(function(){
console.log("DONE!")
});
Please take some time to get a good understanding of asynchronous programming.
In addition to the accepted answer from 10 years ago, with more modern Javascript one can use async/await/Promise() or generator function to achieve the correct behavior. (The incorrect behavior suggested in other answers would be setting series of 3 seconds alerts regardless of "accepting" the alert() - or finishing the task at hand)
Using async/await/Promise():
alert('hi');
(async () => {
for(let start = 1; start < 10; start++) {
await new Promise(resolve => setTimeout(() => {
alert('hello');
resolve();
}, 3000));
}
})();
Using a generator function:
alert('hi');
let func;
(func = (function*() {
for(let start = 1; start < 10; start++) {
yield setTimeout(() => {
alert('hello');
func.next();
}, 3000);
}
})()).next();
You can use the RxJS interval operator. interval emits an integer every x seconds, and take specifies the number of times it emits these numbers.
Rx.Observable
.interval(1000)
.take(10)
.subscribe((x) => console.log(x))
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 1000;
function functionToRun(i, length) {
alert(data[i]);
}
(function forWithDelay(i, length, fn, delay) {
setTimeout(function() {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:
First let's define some essential variables:
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 3000;
Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:
function functionToRun(i, length) {
alert(data[i]);
}
Self-executing version
(function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
Functional version
function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
}
forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it
Just try this
var arr = ['A','B','C'];
(function customLoop (arr, i) {
setTimeout(function () {
// Do here what you want to do.......
console.log(arr[i]);
if (--i) {
customLoop(arr, i);
}
}, 2000);
})(arr, arr.length);
Result
A // after 2s
B // after 2s
C // after 2s
This script works for most things
function timer(start) {
setTimeout(function () { //The timer
alert('hello');
}, start*3000); //needs the "start*" or else all the timers will run at 3000ms
}
for(var start = 1; start < 10; start++) {
timer(start);
}
Here is how I created an infinite loop with a delay that breaks on a certain condition:
// Now continuously check the app status until it's completed,
// failed or times out. The isFinished() will throw exception if
// there is a failure.
while (true) {
let status = await this.api.getStatus(appId);
if (isFinished(status)) {
break;
} else {
// Delay before running the next loop iteration:
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
The key here is to create a new Promise that resolves by timeout, and to await for its resolution.
Obviously you need async/await support for that. Works in Node 8.
for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).
function iAsk(lvl){
var i=0;
var intr =setInterval(function(){ // start the loop
i++; // increment it
if(i>lvl){ // check if the end round reached.
clearInterval(intr);
return;
}
setTimeout(function(){
$(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
},50);
setTimeout(function(){
// do another bla bla bla after 100 millisecond.
seq[i-1]=(Math.ceil(Math.random()*4)).toString();
$("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
$("#d"+seq[i-1]).prop("src",pGif);
var d =document.getElementById('aud');
d.play();
},100);
setTimeout(function(){
// keep adding bla bla bla till you done :)
$("#d"+seq[i-1]).prop("src",pPng);
},900);
},1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
}
PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.
PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..
let counter =1;
for(let item in items) {
counter++;
setTimeout(()=>{
//your code
},counter*5000); //5Sec delay between each iteration
}
const autoPlayer = (arr = [1, 2, 3, 4, 5]) => {
// Base case:
if (arr.length < 1) return
// Remove the first element from the array.
const item = arr.shift()
// Set timout
setTimeout(() => {
console.log('Hello, world!', item) // Visualisation.
autoPlayer() // Call function again.
}, 1000) // Iterate every second.
}
Hey, I know this post is very old, but this code "loops" and adds a delay to it using a recursive method. I don't think you can 'actually' delay a loop itself from iterating based on reading various comments from other people. Maybe this can help someone out! Basically the function accepts an array (in this example). On each iteration the setTimeout Javascript method is called. The function calls itself again indefinitely when the timer of the setTimeout function expires, but on each call the array becomes smaller until it reaches the base-case. I hope this can help anyone else out.
/*
Use Recursive and setTimeout
call below function will run loop loopFunctionNeedCheck until
conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
reRunAfterMs miliseconds and continue loop
tested code, thanks
*/
function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
loopFunctionNeedCheck) {
loopFunctionNeedCheck();
var result = conditionCheckAfterRunFn();
//check after run
if (!result) {
setTimeout(function () {
functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
}, reRunAfterMs);
}
else console.log("completed, thanks");
//if you need call a function after completed add code call callback in here
}
//passing-parameters-to-a-callback-function
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
//test code:
var result = 0;
console.log("---> init result is " + result);
var functionNeedRun = function (step) {
result+=step;
console.log("current result is " + result);
}
var checkResultFunction = function () {
return result==100;
}
//call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));
//result log from console:
/*
---> init result is 0
current result is 5
undefined
current result is 10
current result is 15
current result is 20
current result is 25
current result is 30
current result is 35
current result is 40
current result is 45
current result is 50
current result is 55
current result is 60
current result is 65
current result is 70
current result is 75
current result is 80
current result is 85
current result is 90
current result is 95
current result is 100
completed, thanks
*/
Here is a function that I use for looping over an array:
function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){
if (i < theArray.length && typeof delayAmount == 'number'){
console.log("i "+i);
theFunction(theArray[i], i);
setTimeout(function(){
loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
}else{
onComplete(i);
}
}
You use it like this:
loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
//Do something with item
}, function(i){
//Do something once loop has completed
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
for(var i=0; i<5; i++) {
var sno = i+1;
(function myLoop (i) {
setTimeout(function () {
alert(i); // Do your function here
}, 1000*i);
})(sno);
}
}
</script>
</body>
</html>
Try this...
var icount=0;
for (let i in items) {
icount=icount+1000;
new beginCount(items[i],icount);
}
function beginCount(item,icount){
setTimeout(function () {
new actualFunction(item,icount);
}, icount);
}
function actualFunction(item,icount){
//...runs ever 1 second
console.log(icount);
}

How to Change Interval Time Dynamically in For Loop According to Index/iteration Number?

Since I could not comment, I am forced to write this post. I got the below code which delays/waits exactly 1 seconds or 1000 milliseconds -
let n = 5;
for (let i=1; i<n; i++)
{
setTimeout( function timer()
{
console.log("hello world");
}, i*1000 );
}
But how can I delay it i*1000 seconds instead of fixed 1000 milliseconds so the waiting depends on iteration number ?
For example, if n= 5 , then I want the loop delay 1 second in 1st iteration. 2 seconds in second iteration, and so on.. the final delay will 5 seconds.
While this task could be solved with promises, reactive streams and other cool tools (hey, nobody has suggested using workers yet!), it can also be solved with a little arithmetics.
So you want timeouts in a sequence: 1s, the previous one + 2s, the previous one + 3s, and so on. This sequence is: 1, 3, 6, 10, 15... and its formula is a[n] = n * (n + 1) / 2. Knowing that...
let n = 6;
console.log(new Date().getSeconds());
for (let i = 1; i < n; i++) {
setTimeout(function timer() {
console.log(new Date().getSeconds());
}, 1000 * i * (i + 1) / 2);
}
Here is a function that will show immediately, then 1 second later, 2 seconds after than, 3 seconds after that etc. No special math, no promises needed
const n = 5;
let cnt=0;
function show() {
console.log("call "+cnt,"delay: ",cnt,"sec");
cnt++;
if (cnt > n) return; // we are done
setTimeout(show, cnt*1000 ); // cnt seconds later
}
show()
You can try using async/await (Promises), to serialize your code:
const waitSeconds = seconds => new Promise(resolve => setTimeout(resolve, seconds))
async function main () {
let oldDate = new Date()
let newDate
/*
* If you put 'await' inside the loop you can synchronize the async code, and simulate
* a sleep function
*/
for (let i=1; i<5; i++) {
await waitSeconds(i*1000)
newDate = new Date()
console.log(`Loop for i=${i}, elapsed=${moment(newDate).diff(oldDate, 'seconds')} seconds`)
oldDate = newDate
}
console.log('End')
}
main()
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Took me some time to decipher your question xD, but is this what you want?
This will keep firing console.log with i*1000 delay each time.
so the first time it will be 1 second long (1*1000), next it will be 2 seconds and so on.
let i = 0;
loop = () => {
setTimeout(() => {
console.log(new Date()); // for clarity
i++;
if (i < 10) {
loop();
}
}, i * 1000)
};
loop();
Loop doesn't waits for timeout function to be completed.
So, when the loop runs it schedules your alert for each index.
You can use a function which will run according to your index but scheduled at same time. You can feel the difference of 3 seconds.
function test(i){
setTimeout( function timer(){
console.log("hello world" + i);
}, i*3000);
}
for (let i=1; i<4; i++) {
test(i);
}
Use recursive calls instead of for loop
let i=1;
function a(i) {
if (i > 5)
return
else
b("message", i)
}
function b(s, f) {
setTimeout(function timer() {
console.log(s + " " + f + " seconds");
}, f * 1000);
a(++i);
}
a(i);

How to run setTimeout() with a random interval in each iteration in javascript?

I'm trying to iterate over a string array with a delay of a few milliseconds every step of iteration. Something like below -
var l = ['a', 'b', 'c'];
var delay = 5000;
for(var i = 0;i < l.lenght;i++) {
document.querySelectorAll("a[title='" + l[i] + "']")[0].parentNode.children[0].click();
delay = 5000 + Math.floor(Math.random() * 5000) + 1;
**<WAIT for 'delay' number of milliseconds**
}
I've been able to convert the code to below using setTimeout() method -
var i = 0;
var interval = setInterval(function() {
if (i < l.length) {
document.querySelectorAll("a[title='" + l[i] + "']")[0].parentNode.children[0].click();
i++;
}
else {
clearInterval(interval);
}
//delay = 5000 + Math.floor(Math.random() * 5000) + 1); **NOT SURE where to change the delay variable**
}, delay);
But the delay variable essentially becomes a constant once setTimeout kicks off. How to change the delay variable in each iteration?
You can make a recursive timer function for this:
Try the following :
function displayValue(){
let arr = ['a', 'b', 'c'];
let delay = 1000;
let i = 0;
function timerFunction(i){
if(i === arr.length)
return;
setTimeout(()=>{
console.log(arr[i]);
i++;
timerFunction(i);
}, delay);
delay = delay + 1000 + Math.floor(Math.random() * 4000);
}
timerFunction(i);
}
displayValue();
Could you try replacing that delay variable with a function such as this?
var i = 0;
var interval = setInterval(
function() {
if (i < l.length) {
document.querySelectorAll("a[title='" + l[i] + "']")[0].parentNode.children[0].click();
i++;
}
else {
clearInterval(interval);
}
},
function() {
return 5000 + Math.floor(Math.random() * 5000) + 1;
}
);
setInterval, which you have used in your example, initializes a callback launching every (circa) N ms, where N is fixed. You have to clear it later on with clearInterval.
setTimeout on the other hand means - invoke my callback after ~N time. You could then call another setTimeout inside the callback, with a different N.
as an example:
function callback() {
/*
your logic here
*/
delay = 5000 + Math.floor(Math.random() * 5000) + 1);
setTimeout(callback, delay); // for your "clearInterval" case - just don't invoke this
}
setTimeout(callback, initialDelay);
This thread appears the closest I found to the fundamental question of how to iterate through an array at a random time interval, which isn't as easy as one would think.
Although arguably a little general for the specific question asked, the currently accepted answer looks the closest match to the fundamental question. The code below is a minor modification which looks to provide a random delay on the first pass and logs each random delay after the logging each array value.
function displayValue(){
let arr = ['a', 'b', 'c','d', 'e'];
let delay = Math.floor(Math.random()*10000);
let i = 0;
function timerFunction(i){
if(i === arr.length)
return;
setTimeout(()=>{
console.log(arr[i]);
console.log(`delay was ${Math.floor(delay/1000)} seconds`);
i++;
timerFunction(i);
}, delay);
delay = Math.floor(Math.random()*10000);
}
timerFunction(i);
}
displayValue();
The value of the above modification probably depends on the context.
Interestingly, applying the introduction to forEach from bootcamp provides an alternate solution which is probably closer related to the OP!
var colors = ["red", "green", "blue", "yellow"];
function printArr(x){
var random = Math.round(Math.random()*60000);
setTimeout(() => {
console.log(x);
console.log(`Delay was ${Math.floor(random/1000)} seconds`)
}, random);
};
colors.forEach(printArr);

Categories

Resources