问题变得越来越清晰实际上需要清除的时间间隔

时间:2018-08-23 13:11:32

标签: javascript jquery setinterval

我正在尝试创建一个褪色幻灯片,该幻灯片在jQuery悬停事件上激活。 我的代码是这样的:

var myObj = null;
$('selector').hover(function() {
   // Code to retrieve the image URLs via ajax and construct the slideshow html 
   myObj = setInterval(playMe, 3000);
}, function() {
   clearInterval(myObj);
   myObj = null;
})

var playMe = function() {
   // this just changes the class of each images container, which changes the 
   // opacity from 0 to 1. The fade animation is done using css3 and a transition
}

我遇到的问题是clearInterval不会始终清除,尤其是当您在屏幕上快速移动光标时,会触发快速的鼠标悬停/鼠标悬停事件。然后这会弄乱时间,因为我怀疑有多个playMe正在运行。

反正这附近吗?一种真正确保只运行一次playMe / setInterval的方法?

先谢谢了。

1 个答案:

答案 0 :(得分:1)

您可以先检查myObj是否为null,然后再为其分配setInterval。这样,只有一个setInterval可以运行。

$(function(){
var myObj = null;
$('div#fadeinout').hover(function() {
   // Code to retrieve the image URLs via ajax and construct the slideshow html 
   if(myObj===null){
   myObj = setInterval(playMe, 3000);
   }
}, function() {
   if(myObj){
   clearInterval(myObj);
   myObj = null;
   }
})

var playMe = function() {
   // this just changes the class of each images container, which changes the 
   $('div#fadeinout').toggleClass('fade');
   // opacity from 0 to 1. The fade animation is done using css3 and a transition
}
});
div#fadeinout{
  margin: auto;
  width: 50%;
  height: 200px;
  border: 1px solid black;
  background-color: dodgerblue;
  transition: opacity 1.5s;
}
.fade{
  opacity: 0.25;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fadeinout">
</div>