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/
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).
精彩评论