可以同时使用setTimeout和setInterval吗?

时间:2016-09-29 09:17:03

标签: jquery animation timer

如何延迟执行由30个序列组成的动画,间隔为50毫秒?

$(function() {
    setInterval("anim1()", 50);
    setTimeout("anim1()", 3000); /* doesn't work */
});



function anim1() {
    var oCurBack = $('#fullback div.current');
    var oNxtBack = oCurBack.next();
    if (oNxtBack.length === 0)
        return;

    oNxtBack.addClass('current');
    oCurBack.removeClass('current').addClass('previous');
}   

1 个答案:

答案 0 :(得分:3)

假设:你想在3秒后启动间隔动画

  • 将间隔放入延迟的功能
  • 我使用anim1代替"anim1()",因为使用字符串是隐藏的评估
  • 您可能想停止现在返回的动画
var tId; // have global id to store the interval 
$(function() {
  tId = setTimeout(function() { setInterval(anim1, 50) }, 3000); 
})

function anim1() {
  var oCurBack = $('#fullback div.current');
  var oNxtBack = oCurBack.next();
  if (oNxtBack.length === 0) {
     clearInterval(tId); // clear the interval now we are done
     return;
  }
  oNxtBack.addClass('current');
  oCurBack.removeClass('current').addClass('previous');
}   

要每4秒重复一次动画,请尝试

var tId1, tId2
$(function() {
  tId1 = setInterval(function() { 
    var $divs = $('#fullback div.current');
    $divs.removeClass(current); // remove all current
    $divs.eq(0).removeClass('previous').addClass('current'); // add on the first
    tId2 = setInterval(anim1, 50); 
  }, 3000); 
});


function anim1() {
  var oCurBack = $('#fullback div.current');
  var oNxtBack = oCurBack.next();
  if (oNxtBack.length === 0) {
     clearInterval(tId2); // clear the interval now we are done
     return;
  }
  oNxtBack.addClass('current');
  oCurBack.removeClass('current').addClass('previous');
}