I was using setInterval() and I came across some strange behavior. To illustrate this better, I made a function that simply outputs a value passed to it and increases it by one.
function increase(i){
console.log(i++);
}
However, when I try to use this function inside of setInterval(), it fails to update the variable i.
let i = 0;
setInterval(increase, 1000, i);
When I run that, I simply get 0 printed out every second. However, if I modify the increase function to not take in any arguments, I get the correct output
function increase(){
console.log(i++);
}
Using this version of the function, I get an output of 0, 1, 2, 3... Does anyone have any idea of why that is? I imagine it has to do with the scope of the function, but I'm really not sure what's going on. Is there a way that I can have a function inside of setInterval that takes in an argument and changes it? Or do I simply have to change my function to not receive any arguments and set it to change a variable in the global scope?