Вопрос

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?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top