Kotsu
Kotsu

Reputation: 374

How to use nsITimer in a Firefox Extension?

I am working on a Firefox extension, and wish to make use of a timer to control posting of data every 60 seconds.

The following is placed inside an initialization function in the main .js file:

var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
timer.init(sendResults(true), 60000, 1);

However, when I try to run this I get the following error in the Firefox console:

"Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsITimer.init]" nsresult: "0x80004003"...

And so on. What did I do wrong?

UPDATE:

The following works for my needs, although the initial problem of using nsITimer instead still remains:

var interval = window.setInterval(function(thisObj) { thisObj.sendResults(true); }, 1000, this); }

Useful links that explain why this works (documentation on setInterval/sendResults, as well as solution to the 'this' problem:

https://developer.mozilla.org/En/DOM/window.setTimeout https://developer.mozilla.org/En/Window.setInterval (won't let me post more than two hyperlinks)

http://klevo.sk/javascript/javascripts-settimeout-and-how-to-use-it-with-your-methods/

Upvotes: 2

Views: 1378

Answers (1)

Wladimir Palant
Wladimir Palant

Reputation: 57671

nsITimer.init() takes an observer as first parameter. You probably want to use a callback instead:

timer.initWithCallback(function() {sendResults(true); }, 60000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);

But window.setInterval() is easier to use nevertheless - if you have a window that won't go away (closing a window removes all intervals and timeouts associated with it).

Upvotes: 2

Related Questions