如何多次应用于setInterval循环

时间:2011-02-10 05:20:39

标签: jquery setinterval addclass

这里总新手。我有一个脚本使用setInterval来过滤列表,并每2秒向每个列表项添加/删除一个类。

如何编辑此脚本以便我可以为每个setInterval循环应用不同的时间?

例如:对于第一个列表项,我希望setInterval(或延迟)为3秒,我想要的第二个列表项为1.5秒,依此类推,直到列表完成为止。 ..我需要每个循环的时间不同。怎么办呢? 非常感谢您的帮助。

$(function() {
var $list = $('#animation li');
    $list.filter(':first').addClass('go');

    setInterval(function() {
      if( $list.filter('.go').index() !== $list.length - 1 ) {
      $list.filter('.go').removeClass('go').next().addClass('go');
      }
    else {
      $list.removeClass('go').filter(':first').addClass('go');
      }
   }, 2000);

2 个答案:

答案 0 :(得分:1)

非常原始的例子,但只是显示方法论:

var $list = $('#animation li');
var worker = function(){
  //
  // perform your process(es)
  //

  // only continue on if necessary
  if (continue_working)
    timer = setTimeout(worker, Math.random() * 5 * 1000);
}
var timer = setTimeout(worker, 2000);

// to stop at any time
clearTimeout(timer);

答案 1 :(得分:0)

在setInterval中调用setInterval。

var intervalFunc = new function(){
    if( $list.filter('.go').index() !== $list.length - 1 ) {
  $list.filter('.go').removeClass('go').next().addClass('go');
  }
else {
  $list.removeClass('go').filter(':first').addClass('go');
  }
  // Calculate the next time func
  var timeout = ...
  setInterval(intervalFunc, timeout);
}

setInterval(intervalFunc, 2000);
相关问题