Bubblegumz
Bubblegumz

Reputation: 27

Is it possible to delay a variable in a for-loop with set timeout?

Is it possible to delay the variable value inside window.setTimeout and have the milliseconds value of the timeout be my time variable below?

var value = null;
var time = 5000;

for(var i = 0; i < 30; i++){


  if(value === "a"){
    console.log("You made it!");
  } else {
      console.log("You didn't make it!");
    }

time = time - 100;

}

Upvotes: 2

Views: 258

Answers (3)

Shabbir Ahmed
Shabbir Ahmed

Reputation: 114

You can create a callback function to do so

 var value = null;
 var time = 5000;
 var limit=30;
 var i = 0; 
 function delay(limit, time, callback) {             
      loop();
      function loop(){
          if(value = "a")// it may be a comparison (you are assigning value).
          {
               setTimeout(function(){
                    i++;
                    if (i<=limit && time >= 0){
                        callback("callback after"+time);
                        callback("You made it!");
                        loop();
                    }
                }, time)
           }

           else
           {
                  callback("You didn't make it!");
           }

           time=time-100;
      }
 }


// Calling  a callback function
delay(limit,time, function(callback){
console.log(callback);

Upvotes: 1

Abhishek Panjabi
Abhishek Panjabi

Reputation: 439

You can also use

for(i=0;i<30;i++)
    setTimeout(function(){ 

    alert('hello');
    }, 5000);  

alert('hey');
}

But it'll work in different way. It'll give "hello" right away and after 5 seconds it'll show "hey" .

You can use "clearTimeout()" method to clear timeout .

Upvotes: 1

Nihar Sarkar
Nihar Sarkar

Reputation: 1299

Yes you can do That using setInterval() method:

var myVar=setInterval(function() {
    //codehere
        }, 100);

Here 100 millisecond is the Interval

Use clearInterval() to stop time:

clearInterval(myVar); 

Here myVar is the variable name of setInterval function.

Upvotes: 1

Related Questions