javascript - setInterval() not working as intended -


i wrote function when called returns 5, yet when console.log function inside of setinterval() returns expect. why doesn't work when called?

function countdown(seconds){   var tick = 0;    setinterval(function() {     if (seconds > tick) {       seconds--;       console.log(seconds); //counts down expected.     }   }, 1000);   return seconds;  }  console.log(countdown(5)); //returns undefined. 

also, know settimeout() preferred when swap out setinterval doesn't work @ all. , clarity issue appreciated it.

//returns undefined.

because seconds not defined when function returns. see function body. setinterval isn't called till function returns.

function countdown(seconds){   var tick = 0;    setinterval(function() {     if (seconds > tick) {       seconds--;       console.log(seconds); //counts down expected.     }   }, 1000);    // nothing has assigned seconds till point   return seconds;  } 

you want return that gets resolved @ later point aka. promise.


Comments

Popular posts from this blog

java - Checkbox item adds to spinner -

php - mySQL problems with this code? -

C# MVC AngularJS -