Griffen Hudgens
Griffen Hudgens

Reputation: 3

Increasing setTimeout interval in Javascript

So I have a completely basic html file. What I would like to do is to pick a random number 0-100 with the interval increasing each run through, the way I wanted it done was to have a for loop go through executing the code each time it's ran so the setTimeout increases the delay each time. What I wind up with is a very fast run through with the same delay all throughout. My code that might explain a bit further is as follows:

for ( i = 0; i < Math.floor( Math.random() * 2000 ); i+=100 ) { 
  setTimeout( () => { 
    document.body.innerHTML = ( Math.random() * 101 );
  }, i );
}

The reason I want it done like this is so the code does eventually have a stopping point.

Upvotes: 0

Views: 240

Answers (2)

Sydney Y
Sydney Y

Reputation: 3152

Your loop doesn't seem to reflect what you want to do.

You initialize i to 0

While i is less than (a random number less than 2000)

Set time out to i milliseconds (0, 100, 200, 300...)

Add 100 to i.

Try this:

let random = Math.floor(Math.random() * 2000)
let counter = 10 // number of times to run
for (let i = 0; i < counter; i++) {
  setTimeOut (() => {
    // Do something
  }, random)
  let random += Math.floor(Math.random() * 2000)
}

Upvotes: 0

Mamun
Mamun

Reputation: 68933

Undeclared variables are always global

Declare the variable i with let, this will create a block scoped local variable and will retain the current iteration value in the function:

for (let i = 0; i < Math.floor( Math.random() * 2000 ); i+=100 ) { 
  setTimeout( () => { 
    //document.body.innerHTML += ( Math.random() * 101 );
    console.log(i);
  }, i );
}

Upvotes: 1

Related Questions