Sam
Sam

Reputation: 2341

Javascript: Start setTimeout() only if it hasn't been set already

I have a vibrate function that I want to execute every 3 seconds or so until a button is clicked My way of trying to do this is by having a loop that executes until a condition is false, when the button is clicked, the condition gets set to false. I could use sleep inside my while loop, followed by a call to vibrate, except that I would like to break as soon as the button is clicked, and not have to wait 3 seconds or so.

I am trying to set a timeOut if the device is still vibrating, but I don't want to continually set timeouts, I only want one timeout set at a time, so that a timeout is only set if one is not set already

this.vibrate()
while(this.state.isVibrating){
  if (timeout has not been set){
      setTimeout(this.vibrate(), 3000)
  }                
}
clearTimeout()

Upvotes: 1

Views: 831

Answers (1)

T. Short
T. Short

Reputation: 3614

It sounds like setInterval is a better option here.

let interval;

this.vibrate();

interval = setInterval(this.vibrate.bind(this), 3000);

Then you can have a function execute when the button is clicked that can clear the interval:

function buttonClicked() {
   clearInterval(interval);
}

Just make sure the interval var is in the scope of the buttonClicked function.

Upvotes: 1

Related Questions