在悬停时启动setInterval并在mouseout上停止

时间:2016-04-07 17:54:46

标签: setinterval

我正在尝试在暂停时启动setInterval循环/在mouseout上停止它。鼠标输出有效,但循环最初不仅在悬停时开始。

// Loop trough a set of images
var loop = setInterval(function(){
  rotator.src = dir + num+'.jpg';
  num = (num === len) ? 0 : ++num;
}, delayInMilliseconds);


// The loop should only start on hover
$( '#rotator' ).hover(

  function() {
    console.log( 'hover' );
  },

  // The loop should stop on mouseout
  function() {
    clearInterval( loop );
    console.log( 'no hover' );
  }

)

1 个答案:

答案 0 :(得分:0)

var interval = null;

function animatedCode() {
  rotator.src = dir + num+'.jpg';
  num = (num === len) ? 0 : ++num;}

//Stop and start on hover
$('#rotator').hover(function() {
  interval = window.setInterval(function(){animatedCode()},delayInMilliseconds);

}, function() {
  window.clearInterval(interval);
});