I want to call function with arguement periodically.
I tried setTimeout("fnName()",timeinseconds)
; and it is working.
But when I add an arguement it won't work. eg: setTimeout("fnName('arg')",timeinseconds);
The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.
To call a function periodically in JavaScript, we call the setInterval function. const intervalId = setInterval(() => { console. log("Interval reached every 5s"); }, 5000); to call setInterval with a callback that runs every 5 seconds.
There are two methods for it: setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.
You can add an anonymous function:
setTimeout(function() { fnName("Arg"); }, 1000);
Use an anonymous function, like this:
setTimeout(function() { fnName('arg'); }, time);
In general, never pass a string to setTimeout()
or setInterval()
if you can avoid it, there are other side-effects besides being bad practice...e.g. the scope you're in when it runs.
Just as a side-note, if you didn't need an argument, it's just:
setTimeout(fnName, time);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With