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

2 Answers 2

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
  }    
};
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.