Hey everyone! I’m working on a project and I’m having a hard time with the setInterval
function in JavaScript. I want to make a function run every second, but it’s not working as expected.
I tried this:
let timer = setInterval(myCallback(), 1000);
But it only runs myCallback
once instead of every second. Then I tried:
let timer = setInterval("myCallback()", 1000);
This kind of works, but I get an error saying myCallback is not defined
every second.
Can someone explain what I’m doing wrong here? How can I make setInterval
work properly to run a function repeatedly? Thanks in advance for any help!
I’ve run into this issue before, and it’s a common mistake with setInterval. The problem is in how you’re passing the function to setInterval.
When you use myCallback(), you’re actually calling the function immediately and passing its return value to setInterval. That’s why it only runs once. And using a string like “myCallback()” is generally not recommended as it uses eval() under the hood, which can be risky.
The correct way to use setInterval is to pass the function reference without parentheses:
let timer = setInterval(myCallback, 1000);
This way, you’re passing the function itself, not its result, and setInterval will call it every 1000 milliseconds (1 second).
Remember to clear the interval when you’re done with it:
clearInterval(timer);
Hope this helps solve your problem!