9

I'm trying to understand the strange behavior of this code:

window.setTimeout(window.location.reload, 200);
  • In Firefox this throws a TypeError:

    TypeError: 'reload' called on an object that does not implement interface Location.

  • In Chromium this throws another TypeError:

    Uncaught TypeError: Illegal invocation


These two alternatives work fine:

  • window.setTimeout('window.location.reload()', 200);
  • window.setTimeout(function(){window.location.reload()}, 200)

Why?

Sjon
  • 4,989
  • 6
  • 28
  • 46

1 Answers1

15

This is due to the fact that window.location.reload will be called out of context, so the actual function reload() does not have any reference to the location object.

In JavaScript, if you call a function foo.bar(), the context is foo, so this refers to foo within the function bar.

However, if you assign var a = foo.bar and then call a() (which is still the same function), it will have no context, so this will be undefined. This is what happens when you pass the function as a method parameter.

The usual way to work around this issue is to bind the context:

window.setTimeout(window.location.reload.bind(window.location), 200);

This ensures that the function will always be called in the context of window.location, no matter how it is called.

There is a nice example in the Mozilla docs.

Tobias
  • 7,723
  • 1
  • 27
  • 44