1

I want to create a timer in JavaScript. I see the setTimeout(fn, 100) but unclear how to wrap this so it will clear itself at the end.

I tried doing

var buttonTimer = null; 

$scope.backButton = function() {

    if(buttonTimer === null){
        $history.back();
    }

    buttonTimer = setTimeout(function(buttonTimer){
        buttonTimer = null;
    }, 100);

}

The whole point is to prevent the user from hitting this function too quickly.. and ignoring all subsequent clicks within that 100ms window, at the end of the window, clear the timer and resume accepting clicks

Erik
  • 2,782
  • 3
  • 34
  • 64

2 Answers2

1

Since you are doing angular, I prepared a plnkr for demonstration: http://plnkr.co/edit/5qrslKpmkglXTvEyYgBr?p=preview

Your code is almost Ok, the only problem is that you start a new timeout on every click. The effect is, that the callback fires multiple times and resets buttonTimer.

So the only change is:

var blocker = null;
$scope.backButton = function() {
  if(blocker == null) {
    blocker = setTimeout(function(){
      blocker = null;
    }, 1500);

    // DO YOUR STUFF HERE
  }    
};
mrak
  • 2,826
  • 21
  • 21
0

You can use throttle from lodash/underscore or Ramdajs. for example

$scope.backButton=_.throttle(100,function(){/* do something here */});
marcaia
  • 48
  • 6