I'm practicing using recursion, and there's something I don't quite get. For example, I wrote this simple countdown function, which is supposed to wait until a second elapsed until counting down to the next second.
I first wrote it like so:
function countdown(sec) { console.warn(sec); if(sec > 0) { sec--; setTimeout(countdown(sec), 1000); } } It does not wait one second between each log. This works:
function countdown(sec){ console.warn(sec); setTimeout(function() { sec--; if (sec > 0) { countdown(sec); } }, 1000); }; I don't really understand what's wrong with the first approach. I guess it's something with setTimeout that I don't quite understand, and scoping..?
Thanks in advance for any explanations.
--- edited & working, thanks guys! ---
I didn't know about bind being used as a shorthand.
function countdown(sec) { console.warn(sec); if (sec > 0) { sec--; setTimeout(countdown.bind(null, sec), 1000); } }
setTimeout(countdown.bind(this, sec), 1000);. Herebindwill return a closure i.e) a scoped function which holds yoursecvaluesetTimeout(function(){countdown(sec)}, 1000)Thank you!