在For循环上设置超时/延迟的问题

Issue On Setting Time Out/ Delay on For Loop

本文关键字:延迟 问题 超时 设置 For 循环      更新时间:2023-09-26

您能告诉我如何在以下代码中设置超时/延迟吗?

$(function() {
  var alpha = Array("a","b","c","d","e","f","g","h","i","j","k","l","m","z");
  for ( var i = 0; i < alpha.length; i++ ) {
      $("#box").html(alpha[i].toUpperCase());
}
});

Demo正在这里运行

谢谢

方法如下:

$.each(alpha, function (_, letter) {
    $("#box").delay(500).queue(function (next) {
        $(this).html(letter.toUpperCase());
        next();
    });
});
演示:

http://jsfiddle.net/chq22av6/1/

您可以递归地调用window.setTimeout或使用window.setInterval

它们都接受一个回调方法,该方法将基于计时器(毫秒数)调用。

下面是一个例子:

window.setTimeout(function() {
    // ... do your work ...
    }, 1000 );

您可以在MDN上找到更多信息。

这是一个为您工作的代码,只需使用setTimeout

$(function() {
  var alapha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
    $.each(alapha, function (index, letter) {
        setTimeout(function(){ $("#box").html(letter.toUpperCase())}, index * 100);
    });
});

您可以将100更改为其他值。这是DEMO.

您最好使用

window.setInterval(func, delay[, param1, param2, ...])

调用函数[…],每次调用该函数之间有固定的时间延迟。返回一个intervalID

$(function () {
    // pre-process the letter case transform
    var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
    // cache your jQuery object so we're not recreating it 26 times
    var $box = $("#box");
    // index
    var i = 0;    
    // start an interval and store the id
    var intervalID = setInterval(function () {
        // set element text
        $box.text(alpha[i++]);
        // stop the interval after we've processed 26 letters
        i > 25 && clearInterval(intervalID);
    }, 100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box"></div>

参见:clearInterval(intervalID)