本文介绍了循环setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试围绕一些JavaScript。

I'm currently trying to wrap my head around some JavaScript.

我想要的是要在屏幕上打印的文本,然后计算给定的数字,如下:

What I want is a text to be printed on the screen followed by a count to a given number, like so:

[1秒。暂停]

1

[1秒。暂停]

2

[1秒。暂停]

3

这是我的JS:

$(document).ready(function() {

    var initMessage = "Test";
    var numberCount = 4;

function count(){

    writeNumber = $("#target");

    setTimeout(function(){
        writeNumber.html(initMessage);
    },1000);

        for (var i=1; i < numberCount; i++) {

    setTimeout(function(){
        writeNumber.html(i.toString());
    },1000+1000*i)};

};

 count();

});

这是我的加价:

<span id="target"></span>

当我渲染页面时,我得到的只是Test,后跟4。

When I render the page, all I get is "Test" followed by "4".

我不是JavaScript天才,所以解决方案可能相当简单。任何关于错误的提示都非常受欢迎。

I'm no JavaScript genius, so the solution could be fairly easy. Any hints on what is wrong is highly appreciated.

你可以在这里玩我的例子:

You can play around with my example here: http://jsfiddle.net/JSe3H/1/

推荐答案

你有一个可变范围问题。循环内的计数器( i )仅限于 count 函数。当循环执行完毕时, i s的值为4.这会影响每个 setTimeout 函数,这就是为什么你只看到4。

You have a variable scope problem. The counter (i) inside the loop is only scoped to the count function. By the time the loop has finished executing, is value is 4. This affects every setTimeout function, which is why you only ever see "4".

我会这样重写:

function createTimer(number, writeNumber) {
    setTimeout(function() {
        writeNumber.html(number.toString());
    }, 1000 + 1000 * number)
}

function count(initMessage, numberCount) {
    var writeNumber = $("#target");

    setTimeout(function() {
        writeNumber.html(initMessage);
    }, 1000);

    for (var i = 1; i < numberCount; i++) {
        createTimer(i, writeNumber);
    }
}

$(document).ready(function() {

    var initMessage = "Test";
    var numberCount = 4;


    count(initMessage, numberCount);

});

createTimer 函数确保里面的变量使用 createTimer 提供的新范围捕获循环。

The createTimer function ensures that the variable inside the loop is "captured" with the new scope that createTimer provides.

更新示例:

另请查看以下相关问题:

Also check out these related questions:




  • What's going on under the hood here? Javascript timer within a loop
  • JavaScript closure inside loops – simple practical example

这篇关于循环setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:03