Looping settime

I'm currently trying to circle around JavaScript.

What I want is the text that will be printed on the screen and then counted to the given number, for example:

"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 create the page, all I get is a "Test" followed by a "4".

I am not a JavaScript genius, so the solution can be quite simple. Any hints of what's wrong are much appreciated.

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

+5
source share
3 answers

. (i) count. i 4. setTimeout, "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.

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

:

+6

"2, 3, 4 5 , , i". for-loop i 4, , .

, , . - :

for(var i = 1; i < numberCount; i++) {
    setTimeout((function(x) {
        return function() {
            writeNumber.html(x.toString());
        }
    })(i),1000+1000*i)};
}

- :

var i = 0;
var numberCount = 4;

// repeat this every 1000 ms
var counter = window.setInterval(function() {

   writeNumber.html( (++i).toString() );

   // when i = 4, stop repeating
   if(i == numberCount)
       window.clearInterval(counter);

}, 1000);
+3

, :

var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('target').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}
+1

All Articles