如何重启jquerydelay.fadeout

How to restart jquery delay.fadeout

当用户点击一个按钮时,我们会做一个

$('#element').show().delay(5000).fadeOut();

如果他们在 5 秒内点击按钮,我们想重新启动效果,但正如现在所写的那样,第一个完成而第二个效果没有发生。

根据官方文档,https://api.jquery.com/delay/,延迟是不可取消的:

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

您必须改用超时:

var myTimer;
$('#stop').on('click', function(){
    $('#tohide').show();
     clearTimeout(myTimer);
});
$('#show').on('click', function(){
   $('#tohide').show();
    myTimer = setTimeout(function(){$('#tohide').fadeOut();}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button id="tohide" style="display:none">to hide</button>
<button id="stop">stop</button>
<button id="show">show</button>

您可以使用finish()让之前的动作立即播放完毕。参考http://api.jquery.com/finish/

$('#target').on('click', function(){
  $('#element').finish().show().delay(5000).fadeOut();
});
#element {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="target">Do It</button>
<div id="element">Element</div>