Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to call a javascript function periodically

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);

like image 502
shin Avatar asked Jun 03 '10 11:06

shin


People also ask

How do you run a function periodically?

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.

Do something periodically JavaScript?

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.

How do you call a function periodically in node JS?

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.

How do you call a function repeatedly?

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.


2 Answers

You can add an anonymous function:

setTimeout(function() { fnName("Arg"); }, 1000);
like image 187
Pekka Avatar answered Sep 17 '22 21:09

Pekka


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);
like image 23
Nick Craver Avatar answered Sep 20 '22 21:09

Nick Craver