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

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -