Cannabijoy
Cannabijoy

Reputation: 111

Set a delay between each i = i + 1

I have a for loop that creates an array of the numbers 1-40. When the user holds down the up or down key, the numbers increase or decrease via i++ and i—-.

For some reason, this works great and each number changes at a steady pace- but it’s a bit faster than I would like, and I cannot figure out how to manipulate it.

Is there a JavaScript method to make i = i + 1, stop for a few milliseconds, and then repeat through each iteration?

Upvotes: 1

Views: 69

Answers (3)

8HoLoN
8HoLoN

Reputation: 1142

function delay(ms) { return new Promise((resolve, reject) => setTimeout(resolve, ms))}

(async ()=>{

   for(var i=0;i<40;i++){
       await delay(2000)
   }

})()

Upvotes: 1

Karan
Karan

Reputation: 12619

You can check save press time to global variable like pressTime = new Date(); and check difference with current time as new Date() - pressTime it will return difference in milliseconds so use your desired time interval. If it is larger then your expected time then update value and pressTime also.

Try it below.

document.getElementById('input').onkeydown = keydown;

let i = 0;
let pressTime = new Date();

function keydown(e) {
  if ((e.keyCode == '38' || e.keyCode == '40') && new Date() - pressTime > 1000) {
    e.keyCode == '38' ? i++ : i--;
    pressTime = new Date();
    document.getElementById('input').value = i;
  }
}
<input id='input' type='text' value='0' />

Upvotes: 1

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

Ciao, you can write something like:

function wait() {
  return new Promise(resolve => {
  setTimeout(() => {
  resolve();
}, 1000); // lets say wait one second
});
}

Then on click function you can call:

async buttonClick = () = {
   await wait();
   // increase value and do stuff
};

Upvotes: 1

Related Questions