0

I'm working on a Chrome extension to fetch tweets and I figured that I could use the setInterval() function to make the script run every minute. First I tried giving it the function like this:

setInterval(myFunction(), interval);

But it would only execute my script once. Then out of curiosity I tried declaring the function in the setInterval() function like so:

setInterval(function() {body of my function}, interval);

And that works, but is not a very pretty solution, does anybody any other way of doing this or am I just going to have to deal with it?

Goibon
  • 251
  • 3
  • 17
  • If you're using an event page, [use](http://stackoverflow.com/a/15484602/938089) the [`chrome.alarms` API](https://developer.chrome.com/extensions/alarms.html) instead of `setInterval`. – Rob W Aug 16 '13 at 17:44

1 Answers1

5

Just remove the brackets from the first call. The reason for this is that you need to pass in the function, not the result of the function (what it returns).

When you write the function's name with brackets, it calls the function. When you exclude the brackets, it simply refers to the function like a variable, and so you can pass in your function to the setInterval() function.

setInterval(myFunction, interval);
mash
  • 14,851
  • 3
  • 30
  • 33