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
iis 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
ibecause 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
iif it is block scoped and hence will always stay 1.varis 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();