how to store and reuse a timeout in a jQuery event handler?

一笑奈何 提交于 2021-01-28 18:30:40

问题


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?


回答1:


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));
})


来源:https://stackoverflow.com/questions/29416999/how-to-store-and-reuse-a-timeout-in-a-jquery-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!