Jquery - 每 500 毫秒添加 class

Jquery - Adding class every 500 milliseconds

我想做的是使用 jQuery 每 500 毫秒向位于 "ul" 内的每个 "li" 元素添加一个 class #menu-offcanvas 的 ID。

显然我可以用这个一次性设置所有 ID

setTimeout(function(){
  $('#menu-offcanvas li').addClass('myclass');
},500);

但我需要它做的是遍历那些 "li" 元素并将 class 立即添加到第一个元素,然后每 500 毫秒添加到以下 "li" 元素。

我怎样才能做到这一点?

var timeDif = 0;
$($('#menu-offcanvas li').get().reverse()).each(function () {
    var $el = $(this);
    setTimeout(function () {
        $el.addClass('myclass');
    },500 * timeDif);
    timeDif++;
});

Here 是一个工作示例

使用 setInterval 代替 Timeout 和 .first() 方法,注意代码未经测试

var myVar = setInterval(function(){

  var firstLI = $('#menu-offcanvas li').first();

  if(firstLI){
    $('#menu-offcanvas li:not(.myclass)').first().addClass('myclass');
  }else{
    clearInterval(myVar)
  }

}, 500);

用作函数:

var myInterval = setInterval(function(){
    if($('#menu-offcanvas li:not(.myclass)').first().length) {
        $('#menu-offcanvas li:not(.myclass)').first().addClass('myclass');
    } else clearInterval(myInterval);
}, 500);

DEMO

尝试利用 .queue()

var menu = $("#menu-offcanvas");

menu.queue("addClass", $.map(menu.find("li"), function(el, i) {
  return function(next) {
    $(el).addClass("myclass");
    setTimeout(function() {
      next()
    }, 500)
  }
})).dequeue("addClass");
.myclass {
  background: skyblue;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="menu-offcanvas">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
</ul>

基于 Cari 的回答:

// Define the scope and then run once:
var target = '#menu-offcanvas li:not(.myclass):first';
$(target).addClass('myclass');

// Set interval to run the same thing until there is no need to run any more:
var myInterval = setInterval(function(){
    var item = $(target);
    item ? item.addClass('myclass') : window.clearInterval(myInterval);
}, 500);

我们将查询存储为字符串,以便我们可以 运行 每个间隔。或者,我们可以存储列表项的集合并每隔一段时间将其切片以节省一点 CPU power:

// Define the scope and then run once:
var $target = $('#menu-offcanvas li:not(.myclass)');
$target.first().addClass('myclass');

// Set interval to run the same thing until there is no need to run any more:
var myInterval = setInterval(function(){
    // remove the first item
    $target = $target.slice(1);
    // if the collection's length is still true
    // add the class to the first item
    // else end the timer
    $target.length ? $target.first().addClass('myclass') : window.clearInterval(myInterval);
}, 500);

DEMO