关于在For循环中设置超时/延迟的问题

时间:2014-08-20 02:07:04

标签: javascript jquery

请告诉我如何设置以下代码的超时/延迟:

$(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 is Running here

由于

4 个答案:

答案 0 :(得分:1)

您可以递归拨打window.setTimeout或使用window.setInterval

这两个都接受将根据计时器(毫秒数)调用的回调方法。

以下是一个例子:

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

您可以找到more information on MDN

答案 1 :(得分:1)

这是一种方法:

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

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

答案 2 :(得分:0)

这是一个适合您的工作代码,只需使用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 ..

答案 3 :(得分:0)

你最好的服务

  

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)