16

Just as the title says: setInterval is only firing its callback once.

manifest.json:

{
    //...
    "content_scripts" : [{
        "js" : ["code.js"],
        //...
    }],
    //...
}

code.js (example):

setInterval(alert('only shown once'),2000);

Why, and how I could fix it? The code works well outside of an extension (even in a bookmarklet).

Camilo Martin
  • 37,236
  • 20
  • 111
  • 154

3 Answers3

36
setInterval(function() { alert('only shown once') },2000);

You need to pass a function reference like alert and not a return value alert()

qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • Oh, you're right. There is a problem elsewhere and my attempt at checking it with alert was sloppy. There is a reference in the actual code. – Camilo Martin Jan 23 '12 at 12:58
  • Could you explain why this behaves the way it does? I'm relatively new to JavaScript and would like to learn as much as I can about it. @qwertymk – J2N Apr 12 '13 at 18:10
  • @JLaw [**Take a look at this answer for a better explanation**](http://stackoverflow.com/a/7746522/465546) – qwertymk Apr 14 '13 at 01:39
6

setInterval isn't working at all.

The first argument should be a function, you are passing it the return value of alert() which isn't a function.

Use the three argument version:

setInterval(function,time,array_of_arguments_to_call_function_with);
setInterval(alert,2000,['only shown once']);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Oh, you're right. There is a problem elsewhere and my attempt at checking it with alert was sloppy. There is a reference in the actual code. – Camilo Martin Jan 23 '12 at 12:57
1

The way you wrote it it's wrong:

setInterval() wants a function and a numerical value: setInterval(function(){//your code}, timeInterval).

Dario
  • 5,203
  • 1
  • 23
  • 26
  • You're right. There is a problem elsewhere and my attempt at checking it with alert was sloppy. There is a reference in the actual code. – Camilo Martin Jan 23 '12 at 12:58