Skip to content Skip to sidebar Skip to footer

Only Run A Javascript Function If It Is Not Run Again After A Set Amount Of Time

I have an input which controls the state of an element changing very rapidly. This causes that element to flicker as parts of it change. I am trying to store these state changes a

Solution 1:

What you're looking for is called a debounced function, here is an example with a piece of your code (you're almost there):

//storage for timervar notHappyTimer;

var ifNotHappy = function () {
  changingToHappy = false;

  //removes timer if event fires in less than 500msclearTimeout(notHappyTimer);

  //resets it to attempt again in 500ms
  notHappyTimer = setTimeout(function () {
    if (!changingToHappy) {
      $("#face").text(':(');
    }
  }, 500);

};

As you can see, you just assign the timeout to a variable that clears itself every time the function is fired, then starts the timer again. This ensures that the text change only happens if the function hasn't been fired in 500ms.

Post a Comment for "Only Run A Javascript Function If It Is Not Run Again After A Set Amount Of Time"