ElBiasto
ElBiasto

Reputation: 61

Countdown parameter with Javascript function

I want to create a js function , that counts down to 0 from a parameter s. and displays that at a <p> with the id = count , the function starts via onclick="countdown(60)" from a Button , but somehow it doesn t work. Someone has a idea why ? Thank you for your help.

var count ;
function countdown(s){
    count = s ; 
    while (s > 0) {
        document.getElementById("count").innerText = count ;
    setTimeout(tick(), 1000) ; 
    }
     document.getElementById("count").innerText = "ready" ;

}
function tick (){
    count -- ; 
}

Upvotes: 0

Views: 358

Answers (2)

Curtis
Curtis

Reputation: 103388

Few points:

  • Your while loop will stack the setInterval calls immediately, and therefore they'll all fire after 1 second.

  • Calling setTimeout(tick().. will execute the tick function immediately

See the below as an alternative:

var countdown = function(s){
 
 var c = document.getElementById("count");
  
 var tick = function(){    
    c.innerText = s;
 };
  
 var ready = function(){
   clearInterval(i);
   c.innerText = "ready";
 };
 
 tick();
 
 var i = setInterval(function(){
 	(s>0) ? function(){ s--;tick(); }() : ready();
 }, 1000);
 
 
}

countdown(10);
<div id="count"></div>

Upvotes: 2

Aaron Mahlke
Aaron Mahlke

Reputation: 337

Try this:

var count;
function countdown(s){
	s = count;      // reverse this line and it should work
    while (s > 0) {
        document.getElementById("count").innerText = count ;
    		setTimeout(tick(), 1000); 
    }
    document.getElementById("count").innerText = "ready" ;

}
function tick (){
    count -- ; 
}

Upvotes: 0

Related Questions