javascript – 在特定时间间隔后执行setTimeout for循环

我想遍历一些数字,即每个迭代循环应该在特定时间段之后执行,例如,第一次迭代应该在第一秒执行,下一次应该在2秒后执行,依此类推……

我使用flapper plugin来显示数字.以下是我的片段.

var $lucky = $('.lucky');
$lucky.flapper({
  width: 1,
  chars_preset: 'alpha',
  align: 'right',
  timing: 1000,
  min_timing: 100,
  threshhold: 100,
  animation: 'slow',
  //transform: true,
});

$(document).ready(function() {
  var numbers = ['G', '1', '2', '3', '4', '5', '6'];
  var length = numbers.length;
  for (var i = 0; i < length; i++) {
    console.log(numbers[i]);
    var $lucky = $('#lucky' + [i]);
    setTimeout(function() {
      var $lucky = $('#lucky' + [i]);
      var num = numbers[i];
      $lucky.val(num).change();
    }, 500);
    console.log(i);
  }
});
.header {
  display: inline-block;
}
<div class="container-fluid">
  <input class="header light XXL lucky" id="lucky0" />
  <input class="header light XXL lucky" id="lucky1" />
  <input class="header light XXL lucky" id="lucky2" />
  <input class="header light XXL lucky" id="lucky3" />
  <input class="header light XXL lucky" id="lucky4" />
  <input class="header light XXL lucky" id="lucky5" />
  <input class="header light XXL lucky" id="lucky6" />
</div>

最佳答案 您需要将setTimeout包装为
IIFE.这是因为setTimeout以异步方式运行.在指定时间(即500毫秒)之后即将执行的那一刻,循环将在那时完成.

这是对代码的修改.

$(document).ready(function() {
    var numbers = ['G', '1', '2', '3', '4', '5', '6'];
    var length = numbers.length;
    for (var i = 0; i < length; i++) {
        (function(i){
            console.log(numbers[i]);
            var $lucky = $('#lucky' + [i]);
            setTimeout(function() {
                var $lucky = $('#lucky' + [i]);
                var num = numbers[i];
                $lucky.val(num).change();
            }, (1000 * i));
        })(i);
    }
});

在IIFE中包装超时将捕获每次迭代中的i值.

(function(i){
    // loop will execute whatever inside 
    // with a new value of i in each iteration....
})(i);
点赞