I wanna print variable inside function every 3 seconds using recursion (or loop)
so I’ve tried to
function printVariables() { let num = 1; if (num > 4) { console.log(num); num = 1; } else { console.log(num); num++; } setInterval(printVariables, 3000); }; //i've expected1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ··· //but it's only printed 2, 2, 2, 2, ···
How can I fix that as I expect?
Advertisement
Answer
You need to make a couple of changes to your code:
- Your
i
is getting defined in every function execution, that is not what you want. It will never move to more than 1. So move it outside your function. - Now, in the code below innerPrintVariable has access to
i
because of closures. It is a concept where functions can access variables from their lexical scope. - You will notice that I have used var instead of let. Reason being, let is block scoped. And every iteration will redefine the
i
if it is block scoped and hence will always stay 1.var
is not block scoped.
function printVariables() { var num = 1; function innerPrintVariables() { if (num > 4) { console.log(num); num = 1; } else { console.log(num); num++; } } setInterval(innerPrintVariables, 3000); } printVariables();