samedi 29 avril 2017

Change variable to trigger function 1 time only

I am having problems turning a function on and off based on a variable's value.

Even after I change the variables value to false, it appears to still run the function multiple times.

I am saying by default vibrateToggle = true and if the users mouse is over a certain element and if vibrateToggle = true then run navigator.vibrate(15); function, but after that set vibrateToggle = false so it doesn't keep running in the parent if statement.

Then when the mouse is off the element, set vibrateToggle = true again so that when the mouse is over the element in the future it can trigger vibrateToggle 1 time again.

But it isn't working like that, the navigator.vibrate(15); function is running as if the value if vibrateToggle is always true.

(I am simplified the code to try and make what I am trying to achieve clearer. That is why the first if statement is written like that)

//set variable to true
var vibrateToggle = true;
if (Mouse is over a certain element) {
  //If vibrateToggle is true 
  if (vibrateToggle === true) {
    //trigger vibrate
    navigator.vibrate(15);
    console.log("Vibrate: triggered");
    //After vibrate has been trigger, set vibrateToggle to false to turn it off
    vibrateToggle = false;
    console.log("Vibrate: false. VibrateToggle: " + vibrateToggle);
  }
} else {
  // Turn vibrateToggle back on
  var vibrateToggle = true;
  console.log("Vibrate: true. VibrateToggle: " + vibrateToggle);
}

Aucun commentaire:

Enregistrer un commentaire