Bizarro Zeldman
Bizarro Zeldman

Reputation: 257

How to apply multiple times to setInterval loops

total novice here. I have a script that uses setInterval to filter through a list and adds/removes a class every 2 seconds to each list item.

How could I edit this script so that I can apply different times for each setInterval loop?

For instance: For the first list item, I want the setInterval (or the delay) to be 3 seconds, the second list item I want it to be 1.5 seconds, and so on and so on until the list is finished... I need each loop to be timed differently. How can do this? Your help is greatly appreciated.

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

Upvotes: 1

Views: 1459

Answers (2)

Brad Christie
Brad Christie

Reputation: 101604

Very primitive example, but just showing methodology:

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

Upvotes: 3

xandy
xandy

Reputation: 27411

calling setInterval within 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);

Upvotes: 0

Related Questions