How to use JavaScript setInterval / setTimeout that works in all browsers

Posted by Nordes on August 18th, 2008 filed in HTML, JavaScript

Like usual, inside Internet Explorer you have one way of doing it and inside other browser you have different way of doing it. In fact, they looks almost the same, but when it comes to send parameters to the function pointer in your interval you may have some troubles to be browser compliant.

Here’s how internet explorer define the setInterval() function:

1
var iTimerID = window.setInterval(vCode, iMilliSeconds [, sLanguage])

You can find how to work with it by going on the this site msdn.microsoft.com.

Inside Firefox, you can actually instead of the third parameter, submit 1 or more parameter that will be used when calling back your function. By going on Mozilla specification page, you can find how to set interval on Mozilla browsers.

1
2
intervalID = window.setInterval(func, delay[, param1, param2, ...]);
intervalID = window.setInterval(code, delay);

Resolution
If you want to be able to send your function the proper parameter, the best way is be doing an inner function parameter calling the function you want to call. What does that mean? It means that you will be able to call a function using your context variables.

Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var myIntervalId = null;
 
function myFunction(a, b, c){
	var xyz = 3;
	// some code
 
	// Set the interval with an anonymous method calling your application method.
	myIntervalId = setInterval(
		function(){ 
			intervalFunction(xyz, 12); 
		}, 1000);
 
	return myIntervalId;
}
 
function intervalFunction(param_1, param_2){
	if (param_1 != 0){
		clearInterval(myIntervalId); // Stop the interval
		// some code here
	}
	param_1 = param_1 -1;
	// Some code here
	alert(param_1);
}
 
myFunction(1,2,3); // Do the call to a function;

In this small example with almost no code, you will actually wait 3 seconds and after it will stop the counter and do what you want to do. Also, between those interval, you will receive a pop-up saying how much time you have left before the countdown stop.

This is nothing extraordinary, but if you plan on using interval using context parameters, be aware that you should do this instead of anything else.


One Response to “How to use JavaScript setInterval / setTimeout that works in all browsers”

  1. buy levitra canada Says:

    signposted laxmi united cards amend financings upkeep escaping gallagher clocked operator alekssandr

Leave a Comment