user3474711
user3474711

Reputation: 41

My JavaScript loop is an infinite loop?

I'm new to programming, so please don't be harsh with my skills. Anyways, here is my code, I'm attempting to make a simple countdown loop.

var number = 30;
var countdown = true;

while(countdown === true) {
    subtract();
    if(number === 0) {
        countdown = false;
    }
}

function subtract() {
    setTimeout(function() {
        console.log(number);
        number = number - 1;
    }, 1000);
}

What did I do wrong?

Upvotes: 2

Views: 102

Answers (4)

Shahar
Shahar

Reputation: 11

When using the setTimeout function you actualy call a function after X miliseconds (in this case X=1000, which is 1 second).

'While' is the function you want to do the countdown with, right? So in your subtract function just write:

console.log(number);
number = number - 1;

You can also drop the subtract function and just write:

while(countdown === true) {
    console.log(number);
    number = number - 1;
    if(number === 0) {
        countdown = false;
    }
}

Or drop the while function:

function subtract() {
    id(countdown === true)
    setTimeout(function() {
        console.log(number);
        number = number - 1;
        subtract();
    }, 1000);
    else countdown = false;
}
subtract();

Upvotes: 0

Malk
Malk

Reputation: 11983

setInterval is the function to set a function to run periodically. https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval

var number = 30;
var countdown = true;
var timer;

function update(){
   console.log(number);
   number = number - 1;
   if (number === 0)
      clearInterval(timer);
}


timer = setInterval(update, 1000);

Upvotes: 1

user2981107
user2981107

Reputation: 77

although javascript is called asynchonous in this case it does not call the subtract function until the first one is finished. (details http://ejohn.org/blog/how-javascript-timers-work/)

this should work

var number = 30;

setTimeout(function() {
    console.log(number);
    number = number - 1;
}, 1000);

Upvotes: 1

000
000

Reputation: 27227

Javascript has function-level block execution. One function runs to completion before another function is given ability to execute. Your while loop is maintaining the execution baton, so the other functions in setTimeout are never given a chance.

Upvotes: 2

Related Questions