FireFox setInterval weirdness

I wrote a script the other day with a function that has an optional parameter. I used the usual if (typeof param == 'undefined') to detect if the parameter was given or not, and it all worked fine. Until I plugged it in to the setInterval function. That’s when Firefox started to show really odd behavior.

As a minimal example to replicate this behavior:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl" lang="nl">
	<head>
		<title>FF setInterval bug?</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	</head>
	<body>
		<div id="test"></div>
	</body>
	<script type="text/javascript">
		function test(n) {
			document.getElementById('test').innerHTML=document.getElementById('test').innerHTML + n + ', ';
		}
		setInterval(test, 500);
	</script>
</html>

(or see it in action, here)

Chrome, Opera, IE and Safari all show what you would expect: undefined, undefined, undefined, undefined, (etc)

But … Firefox spews out what seems like a random sequence of numbers! E.g.: -2, 0, 1, 1, 0, 0, 1, 38, -3, -1, 2, 0, 0, 0, 1, 1, 0, 1, (etc)

There seems to be no pattern at all, and it’s different every time you refresh the page …

I’ve solved the problem for now by replacing


setInterval(test, 500);

with


setInterval(function() { test(); }, 500);

which does yield the expected result (undefined, undefined, undefined, …), but I’m still curious if anyone has ever seen this and/or knows where there this weird behavior is coming from.

PS. setTimeout(test, 500) shows the same behavior

Odd indeed, though it is expected behaviour according to Mozilla:

https://developer.mozilla.org/en/window.setInterval:

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.

I just ran a quick test and if you’re using the setInterval method to pass in the params (e.g. setInterval(fn, 200, param1)) you will get the expected results. But I do believe IE has issues with this. Using an anonymous function as you have done is the correct solution :slight_smile:

Ah, that explains a lot! Pretty odd though that it would report negative numbers (i.e. the event was fired too soon – how do they manage that?!)

The setInterval(fn, 200, param1) won’t help me in this case by the way, because my intention is ~not~ to pass any parameter, so I’d have to omit param1, which takes us back to square 1 hehe.

Anyway, both the issue and the weirdness are resolved!

Thanks, John :slight_smile: