fip fip - 2 months ago 12
jQuery Question

Using both setTimeout and setInterval possible?

How can I delay the execution of an animation that is composed of 30 sequences with an interval of 50ms?

$(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');
}

Answer

Assumption: You want to start the interval animation after 3 seconds

  • put the interval into a function you delay
  • I use the anim1 instead of "anim1()" since using the string is a hidden eval
  • you likely want to stop the animation where you return now

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');
}   

To repeat the animation every 4 secs try

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');
}