Search code examples
javascripttimeoutcountdowneaseljscreatejs

Countdown in JavaScript with variable


I'm using CreateJS / EaselJS building my content.

I want to insert a short delay until some extra content is available for the user. It is important to show the remaining time!

My solution:

myLabel.text = "5";
setTimeout(function(){ myLabel.text = "4";
 setTimeout(function(){ myLabel.text = "3";
  setTimeout(function(){ myLabel.text = "2";
   setTimeout(function(){ myLabel.text = "1";
    setTimeout(function(){
     myLabel.text = "0";
     myButton.addEventListener('click', myFunction);
    }, 1000);
   }, 1000);
  }, 1000);
 }, 1000);
}, 1000);

Is that possible with shorter code?

Bonus: Pass a variable as countdown duration (ex. 5000 for 5 sec.)

I hope for a quick answer, Simon


Solution

  • use setInterval instead:

    var myNumber = 5;
    myLabel.text = myNumber;
    var myInterval = setInterval(function() {
         myLabel.text = --myNumber;
         if (myNumber === 0) {
             myButton.addEventListener('click', myFunction);
             clearInterval(myInterval);
         }
    }, 1000);