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

Answer from Daniel Vassallo on Stack Overflow
Top answer
1 of 16
974

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

2 of 16
345

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.

🌐
freeCodeCamp
forum.freecodecamp.org › t › javascript-help-looping-with-delay › 332667
JavaScript help - looping with delay - The freeCodeCamp Forum
December 12, 2019 - Hi guys and gals, I wonder if you would be able to help me. I have a function that removes all items in a cart, the code (while loop) works, but I want to remove one at a time, with a visible delay (say 200ms). It looks like an IIFE would be the way to go with a setTimeout function, but I can’t ...
Discussions

Adding a delay to each iteration of loop?
It'd be easier to make it an async function and await a setTimeout-managed delay. const delay = (ms) => new Promise(r => setTimeout(r, ms)) // helper func const bubbleSort = async (data) => { // <- now async // ... for (let i = 0; i < len; i++) { await delay(1000) // <- pauses for 1 second // ... Note that this would now return a promise that would resolve when the sort was complete rather than an immediate sorted result. You could also make it a generator function and instead of awaiting, using yield. This would allow the caller to determine the timing at which each iteration is handled giving the caller more control vs having something like a constant 1 sec baked in. More on reddit.com
🌐 r/learnjavascript
4
1
May 26, 2021
Javascript delay with while loop - Stack Overflow
the site is here I'm trying to create an animated button by moving the position of the background using Javascript when the user clicks the button. However, instead of slowly scrolling, the button ... More on stackoverflow.com
🌐 stackoverflow.com
How to pause for 1 second in between the iterations of my loop
How do I pause for 1 second in between every iteration of my while loop without changing up anything but adding some code? function getStone() { while (true) { let stoneChance = Math.floor(Math.random() * 10); if (stoneChance == 5) { stoneAmt++; document.getElementById("stone_count").innerHTML ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
November 5, 2022
Create a pause inside a while loop in Javascript - Stack Overflow
I would like to create a pause inside a while loop so that I can create n animations that each appear 3 seconds after the other. I've tried the following, but it doesn't work. Would love to have so... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Educative
educative.io › answers › how-to-add-a-delay-in-a-js-loop
How to add a delay in a JS loop
This becomes possible by adding the setTimeout() method in JavaScript. In this Answer, we will cover how to add a delay in a JS loop after every iteration and how to add an instant delay only at the start of the loop.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-add-a-delay-in-a-javascript-loop
How to add a delay in a JavaScript loop? - GeeksforGeeks
May 31, 2024 - Example: Below given program will print 0 to 9 in console after 2 seconds delay to each number using do-while loop. JavaScript · <script> let i = 0; do { task(i); i++; } while (i < 5); function task(i) { setTimeout(function() { console.log(i); ...
🌐
Edureka Community
edureka.co › home › community › categories › web development › java-script › how do i add a delay in a javascript loop
How do I add a delay in a JavaScript loop | Edureka Community
September 20, 2020 - I would like to add a delay/sleep inside a while loop: I tried it like this: alert('hi'); for(var ... time alert('hello') and so on. How to do it?
🌐
Reddit
reddit.com › r/learnjavascript › adding a delay to each iteration of loop?
r/learnjavascript on Reddit: Adding a delay to each iteration of loop?
May 26, 2021 -

Hi everyone,

I'm desperate and in need of some guidance :P

I'm trying to create a classic algorithm visualiser kind of thing (in React), and am now implementing the first of the list, bubblesort.

The idea is to add a small delay after each sorting action, so that there's enough time for the user to see the animation unfolding.

const bubbleSort = (data) => { //data is array of nums
  const newData = [...data]
  let len = data.length
  let swapped
  do {
    swapped = false
    for (let i = 0; i < len; i++) {
      setTimeout(() => { //delaying action
        if (newData[i] > newData[i + 1]) {
          let tmp = newData[i]
          newData[i] = newData[i + 1]
          newData[i + 1] = tmp
          console.log(newData)
          swapped = true   //! eslint unsafe reference
        }
      }, i * 1000) // add enough time for each action to be done in succession
    }
  } while (swapped)

  console.log("done?") //!Triggers immediately - because of asynchronicity

  return newData
}

export default bubbleSort

The main issue is that it stops after sorting just a single value. However, commenting out the setTimeout wrapper makes the sorting happen fully and perfectly. So I'm guessing something is going wrong with the asynchronicity?

Another issue that I'm getting is an eslint no-loop-func warning: "Function declared in a loop contains unsafe references to variable swap". I read through the eslint docs and understand that it's being flagged because of possible scope complications, but I have no idea how to fix it in this implementation.

I looked through this and this, but am having a hard time relating and applying what they say to my case.

I hope someone can point me in the right direction with this (it's been a long day trying to figure this out). All I need is to delay each iteration.

Thanks in advance!

🌐
Atomizedobjects
atomizedobjects.com › blog › javascript › how-to-make-a-loop-wait-in-javascript
How to make a loop wait in JavaScript | Atomized Objects
The for loop itself is pretty standard and nothing special, the only part that is different here is that we are calling await delay(1000) from within the for loop block which is waiting for the delay function that we created to complete which will take 1 second because we are passing in 1000 ...
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-add-delay-in-a-loop-in-javascript
How to add delay in a loop in JavaScript?
August 16, 2023 - <html> <head> <title>How to add delay in a loop in JavaScript?</title> <script> function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function delayedLoop() { var items = [1, 2, 3, 4, 5]; var delay = 1000; // 1 second for (var i = 0; i < items.length; i++) { // ...
🌐
Coding for SEO
codingforseo.com › blog › how to add a delay in a javascript loop
How to Add a Delay in a JavaScript Loop | Coding for SEO
June 4, 2024 - // This line is only needed if you are using a version of Node.js that is older // than 17.5. import fetch from "node-fetch"; import fs from "fs"; // Here's the sleep timer. const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); async function fetchData(urls) { // For the purpose of the example, we'll sleep for 4 seconds to clearly show // that it's working. const delay = 4000; const output = []; for (let i = 0; i < urls.length; i++) { console.log("fetching", urls[i]); // await the response and extract the JSON data as a JavaScript object. const response = await fetch(urls[i]); const data = await response.json(); // Push the data into the output array. output.push(data); // This displays the data to show that the delay is really working. console.log("got this data:", data); // Await the sleep timer before going back to the beginning of the loop.
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript while loop with delay
JavaScript while loop with delay - Tutorial - By EyeHunts
June 23, 2023 - function countdownTimer(seconds) { var counter = seconds; function iteration() { console.log('Seconds remaining:', counter); counter--; if (counter >= 0) { setTimeout(iteration, 1000); // Delay of 1 second (1000 milliseconds) } else { console.log('Countdown complete!'); } } iteration(); // Start the countdown } countdownTimer(5); // Start the countdown from 5 seconds ... The loop continues until the counter reaches 0, at which point the condition becomes false.
🌐
Quora
quora.com › How-do-I-create-a-delay-by-using-a-“while”-statement
How to create a delay by using a “while” statement - Quora
Answer (1 of 6): I remember when PCs and MS DOS became popular, people would code “busy-wait” loops like this: [code]for (x=0; x
🌐
YouTube
youtube.com › watch
How to Delay a loop in javascript synchronously - YouTube
Hello Guys,I recently worked for https://graphicalstructure.codesThere i found an efficient way to delay a loop and no more need of recursions.Promise functi...
Published   September 4, 2020
🌐
Scottie's Tech.Info
scottiestech.info › home › programming › javascript fun: looping with a delay
JavaScript Fun: Looping with a Delay | Scottie's Tech.Info
July 1, 2014 - Now, most likely, in order to alert “Cheese!” ten times (with a 3-second delay between each alert), the first thing you’ll probably try is this: for (var i = 1; i < 10; i++) { setTimeout(function () { alert("Cheese!"); }, 3000); } The above ...
🌐
The Web Dev
thewebdev.info › home › how to create pause or delay in a javascript for loop?
How to create pause or delay in a JavaScript for loop? - The Web Dev
September 2, 2022 - As a result, we see that the numbers are logged after a 2 seconds delay between each iteration. To create pause or delay in a JavaScript for loop, we should use await with a for-of loop.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-delay-a-loop-in-javascript-using-async-await-with-promise
How to delay a loop in JavaScript using async/await with Promise ? | GeeksforGeeks
September 27, 2024 - By wrapping a setTimeout() inside a Promise and using await, you can pause execution at each iteration, creating delays between loop iterations for asynchronous tasks without blocking the main thread. async and await in JavaScript are used for ...
🌐
Kirupa
kirupa.com › html5 › timers_js.htm
Timers in JavaScript
There are no ands, ifs, or buts about it. The concept of delaying execution or deferring work to later isn't a part of JavaScript's default behavior. We kinda sorta saw this when looking at loops earlier.