Quick tip: IE6 setTimeOut invalid argument error

In this quick tip I'll show you how to avoid a common pitfall with IE and the javascript setTimeOut method.

Recently I was having trouble with a few lines of javascript in which I used the setTimeOut method to defer the running of a function called goToLocation. Here's the code:

var t = setTimeout(goToLocation('/download/'),2000);

In Firefox everything appears to be fine and the code executes as expected. However, IE will throw an error "Invalid argument". For once this is a good thing...

Why the error?

Whilst it would be easy to blame this on Internet Explorer, in fact the reason for this error is that we're using the setTimeOut() method incorrectly.

According to a well respected reference setTimeOut expects either:

  1. A "script expression" - either a line of code as a string or an actual function (eg: myFunction() ).
  2. A reference to a function - ie: a function name without the parenthesis

In the example above we're trying to call the function goToLocation() and also pass one argument to the function. The issue is with the way we're passing the arguments.

The problem with arguments

According to various references, trying to pass arguments in the first parameter of setTimeOut() is not valid. The method won't be able to interpret the function call and will throw an error.

In fact, officially setTimeOut() accepts 3 parameters:

  1. A function expression or reference (as above)
  2. An interval in milliseconds
  3. A set of arguments to pass to the function defined in parameter #1

Knowing this then we should be able to rewrite our code thus:

var t = setTimeout(goToLocation,2000, '/download/');

However, this syntax is not supported by explorer and will fail. 

Solution - Fixing the Internet Explorer Error

So how do we get the code working?

It seems there is a simple, elegant solution to this problem. Simply wrap your function call in an anonymous function and everything will work as expected.

Therefore my code from the previous example now becomes:

var t = setTimeout(function() {goToLocation('/download/')},2000);

Hope this helps someone and let me know if there's a way I can improve my code.

Grow your business

Find out how Deep Blue Sky can grow your business.

  1. Digital benchmark
  2. Digital roadmap
  3. Digital engineering

Write a comment.