siemaeniu500
siemaeniu500

Reputation: 115

javascript counter using for loop

I've created a simple counter using javascript but there is a problem Field "display" starts from 1, but it should start from 100 and goes low. The console logs shows values correctly from 100 to 1. I have to use loops to do this tasks, so please not replace it using recursion :) Also the timeout is for sure does not equal to 100ms, it's more

function wyswietlLiczbe(j) {
    setTimeout(function() {
        document.getElementById("display").innerHTML = j;
    }, 100);
}

for (var i= 100; i > 0; i--){
    console.log(i)
    wyswietlLiczbe(i);
}
<p id="display"></p>

Upvotes: 1

Views: 94

Answers (4)

Aswin Ramesh
Aswin Ramesh

Reputation: 1674

you can use setInterval instead

function wyswietlLiczbe(j) {
    x = setInterval(function() {
        if(j==0) clearInterval(x);
      document.getElementById("display").innerHTML = j--;
    }, 100);
}
wyswietlLiczbe(100);

Upvotes: 0

Faan Veldhuijsen
Faan Veldhuijsen

Reputation: 106

I don't know exactly what you want but I think this is what you're looking for.

function wyswietlLiczbe(j) {
    if (j >= 0) {
        setTimeout(function() {
            document.getElementById("display").innerHTML = j;
            j--;
            wyswietlLiczbe(j);
        }, 100);
    }
}

wyswietlLiczbe(100);
<p id="display"></p>

Upvotes: 1

splitwire
splitwire

Reputation: 297

Build the conditional into the function which will execute after the timeout.

var elmD = document.getElementById("display");

function wyswietlLiczbe(j) {
    setTimeout(function() {
      elmD.innerHTML = j;

      j--;

      if(0 <= j ) {
        wyswietlLiczbe(j)
      }
    }, 100);
}

wyswietlLiczbe(100);

Upvotes: 1

IrkenInvader
IrkenInvader

Reputation: 4050

Since the loop executes immediately, you need to wait an increasing amount of time for each number. This will queue up the innerHTML modifications.

As it is now, after a 100ms wait all 100 wyswietlLiczbe are executed in rapid succession.

function wyswietlLiczbe(j, waitTime) {
    setTimeout(function() {
        document.getElementById("display").innerHTML = j;
    }, waitTime);
}

for (var i= 100; i > 0; i--){
    console.log(i)
    wyswietlLiczbe(i, (101 - i) * 100);
}
<p id="display"></p>

Upvotes: 3

Related Questions