取消/停止超时功能

scm*_*y22 1 javascript settimeout

我有一些 javascipt (jQuery),当单击按钮时,我在 #myDiv 中淡出,然后在 5 秒后使用超时函数再次淡出。它工作正常,但如果用户在我的超时内的淡入淡出功能运行之前再次单击该按钮,我需要超时停止并基本上重新开始。

我认为答案是首先运行一个函数来清除超时,但我无法完成这项工作。

$('button').on('click', function() {

  //need function here to stop the timeout if running

  $("#myDiv").fadeIn(slow);

  setTimeout(function(){
    $("#myDiv").fadeOut(slow);
  }, 5000);

});
Run Code Online (Sandbox Code Playgroud)

小智 5

如果已经设置,您必须清除超时:

var to = null;
$('button').on('click', function() {

  if(to){
     clearTimeout(to);
  }
  //need function here to stop the timeout if running

  $("#myDiv").fadeIn(slow);

  to = setTimeout(function(){
    $("#myDiv").fadeOut(slow);
  }, 5000);

});
Run Code Online (Sandbox Code Playgroud)

clearTimeout()函数删除超时,因此如果用户在按钮上单击两次,第一个超时将被删除,只有第二个实例将被执行。