1

I have a button, when clicked it will start a timeout function, if it is clicked again before the function is executed, I want the former timeout to be cleared thus it can start a new timeout.

Demonstration code:

<div id='a'>lorem</div>

$('#a').click(function(){
  //code to clear previous timeout
  //This is not working: clearTimeout(timeout);
  var timeout = setTimeout(function(){
   //do something
  },5000);
  return timeout;    
})

The only way I can think of is make timeout global, but global is ugly.

Is there any better way to do this? And in the above codes, where is timeout being returned to? In which scope I can use it?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
shenkwen
  • 3,536
  • 5
  • 45
  • 85
  • 1
    Use an IIFE or module pattern (ie. put the JavaScript code to add the click in a function) to make the timeout a non-global variable in an outer (and longer lasting) scope. – user2864740 Apr 02 '15 at 15:45
  • possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – user2864740 Apr 02 '15 at 15:46
  • 1
    For the secondary question: see http://stackoverflow.com/questions/11184276/return-false-from-jquery-click-event and http://stackoverflow.com/questions/4379403/jquery-event-handlers-return-values?rq=1 for the returned value meaning (and how to do as much in a 'modern way', although returning false will still work, but timeout will never be a falsey value so..) – user2864740 Apr 02 '15 at 15:48

1 Answers1

7

There are two alternatives to global variables that you can use here :

1 an IIFE creating a local scope :

(function(){
    var timer;
    $('#a').click(function(){
      clearTimeout(timer);
      timer = setTimeout(function(){
          //do something
      },5000);
    })
})();

2 jquery data attached to the element

$('#a').click(function(){
  clearTimeout($(this).data('timer'));
  $(this).data('timer', setTimeout(function(){
      //do something
  },5000));
})
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • method 2 not work on JQ 3.1.0+: Uncaught TypeError: Cannot create property 'guid' on number '1' – Mashiro Feb 20 '19 at 12:46