Question

I have a jQuery waypoint trigger and I need to add a new class to the same element every second a set number of times. How I can I set a timer like function in jQuery?

Was it helpful?

Solution

Given a list of classes and some element, lets call it <div id="myEl"></div>, you can do the following:

var $el      = $('div#myEl'),
    classes  = ['red', 'green', 'blue', 'yellow'],
    interval = window.setInterval(function() {
      if (classes.length === 0)
        window.clearInterval(interval);

      $el.addClass(classes.shift());
    }, 1000);

Here's a DEMO

The key is to use window.setInterval(fn, interval), which accepts a callback function fn that is executed every interval milliseconds. You'll notice that I've added a conditional line here for when the classes array is empty.

Basically, the window.setInterval function returns a unique integer id which corresponds to the new interval that you have instantiated. To cancel the interval (assuming you don't want it to run forever), simply pass this id to the window.clearInterval function. In this case, I want to cancel the interval loop when I have added all of the classes in the classes array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top