Need help for loop like sleep or wait function

Hello folks ,

I am working on project that requires some immediate help , i stuck :confused: in this could not proceed with next part for program

Want to create delay in javascript loop like sleep or wait function

sample -

note:- setTimeout() not working
for(var start = 1; start < 10; start++) {

//wait for some minute

}

Thanks

Hi there,

Welcome to the forums :slight_smile:

What exactly is not working for you?

I would have thought something like this should do the job:

for(var i = 1; i < 10; i++) {
  (function(i){
    setTimeout(function(){
      console.log("Hello " + i);
  }, 500 * i)
 })(i);
}

I would have thought something like this would be more interesting :slight_smile:


for(var i = 1; i < 10; i++) {
    (function(i){
        console.log("Hello " + i);
        i=i+10;
        console.log("Hello " + i);
    })(i);
}

I shall fall on my sword :slight_smile:

for(var start = 1; start < 10; start++) {
  (function(i){
    setTimeout(function(){
      console.log("Hello " + i);
    }, 500 * i)
  })(start);
}

Thanks!

Hehe, no need. :slight_smile:

Shadowing variables is tricky. The simple way JavaScript lets you write code often hides something a bit more complex. It pays to be more explicit about whatโ€™s going on: passed by value function mechanism == implicit variable declarations (parameters), combined with variable shadowing.

Add this to the closure concept involved in the first code and you got a solid list for head scratching. :slight_smile:

Without IIFE it should make more sense:


for(var counter = 1; counter < 10; counter++) {
  message(counter);
}

// it doesn't work in IE < 9
//function message(ratio) {
//    setTimeout( hello, 500 * ratio, ratio);
//}

// works everywhere
function message(ratio) {
    setTimeout(hello.bind(null, ratio), 500 * ratio);
}


function hello(increment) {
    console.log("Hello " + increment);
}