I know this may be an easy answer, but I am having trouble using my function with setInterval. Here is what I have so far:
function countUp(n) {
console.log(n++);
}
setInterval( function() { countUp(10); }, 1000);
If I move my variable outside the function and increment that value, it will work. However, I want to be able to set the number to anything when I call the function countUp. The above code just keeps logging 10.
EDIT:
Is there any way to pass an argument to this function and make it work with setInterval without having to declare a global variable?
You need to increment a variable in the enclosing scope of the function:
Update: Here’s a strategy that doesn’t involve a global variable:
As I noted, the counter just needs to be in the enclosing scope, not the global scope. So passing it into a function that can reference it in a closure will work fine here.