Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

"Test"

[1 sec. pause]

"1"

[1 sec. pause]

"2"

[1 sec. pause]

"3"

This is my 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();

});

This is my markup:

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

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

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
423 views
Welcome To Ask or Share your Answers For Others

1 Answer

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".

I would rewrite it like this:

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);

});

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

Updated Example: http://jsfiddle.net/3wZEG/

Also check out these related questions:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...