Skip to content
Advertisement

How can I print variables inside function every 3 seconds using recursion?

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:

  1. 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.
  2. 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.
  3. You will notice that I have used var instead of let. Reason being, let is block scoped. And every iteration will redefine thei 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();

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement