Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Firefox setInterval callback arguments differ from other browsers?

I tested this script in every browser on Win 7. It doesn't work on Firefox only (ver. 3.6.13).

The alert box returns "undefined" in all the browsers except for Firefox that returns a random number. Here is the script

function nextSlide(nav){
    alert(nav);
}

jQuery(function(){
    var set = setInterval(nextSlide, 2000); 
});

Here is a live demo

like image 762
manuel Avatar asked Mar 09 '26 04:03

manuel


2 Answers

The extra argument is the number of milliseconds that the callback was late. From the documentation:

Callback arguments

setInterval() will pass the number of milliseconds late the callback was called into the callback function, which can confuse it if it expects something else as an argument. To sidestep that problem, use an anonymous function to call your callback.

The fix is to write this instead:

var set = setInterval(function() { nextSlide(); }, 2000);
like image 122
Mark Byers Avatar answered Mar 11 '26 18:03

Mark Byers


Mark Byers is correct in explaining it with the Mozilla documentation.

However, this is a Firefox extension. The WindowTimers interface -- at least as it is in HTML5 working draft -- actually has a different requirement. Of course, since this is a volatile domain...

handle = window . setInterval( handler [, timeout [, arguments ] ] )

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

Therefore, Firefox could be seen in violation of this as arguments.length is 1 even though "no arguments" were passed.

I believe for HTML4 it's just defacto implementations without any "official standards" defined -- or at least none that I know of -- and, in which case, Firefox can do pretty much whatever it pleases. I would be happy for a correction/reference.

Edit:

Firefox does support the argument pass-through, as noted by Neil and arguments.length is always one more than the number of arguments passed to account for the "offset" data -- no magic is being done on arguments.length (which would be really scary in and of itself).

This is important to keep in mind: don't use and/or be careful when using arguments.length inside a timer callback or face browser differences. (This is inline with other event callbacks).


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!