Setinterval Not Working As Expected With Counting Function
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++); } setI
Solution 1:
You need to increment a variable in the enclosing scope of the function:
var n = 10;
functioncountUp() {
console.log(n++);
}
setInterval(countUp, 1000);
Update: Here's a strategy that doesn't involve a global variable:
functioncountUp(start) {
returnfunction() {
console.log(start++)
}
}
setInterval(countUp(10), 1000);
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.
Post a Comment for "Setinterval Not Working As Expected With Counting Function"