I would love some insight into the error I am seeing in Safari and Chrome with the following line of code:
setTimeout(window.location.reload, 250);
This fails because you're missing the location
context (the function's this
), when passing it your way.
You would have to bind
the context, before you can use it like this, for example with the underscore.js bind method
var boundReload = _.bind(window.location.reload, window.location);
setTimeout(boundReload, 500)
It's the same with any other function that is usually called from it's containing object like console.log
Because this
must be bound to location
when you call reload
. It's same as trying:
var reload = window.location.reload;
reload();
this
would be window
in non-strict mode and undefined
in strict mode which are both invalid.
in non-old browsers you can do instead:
reload.call( location )
or in your example:
setTimeout( window.location.reload.bind( window.location ), 1000 )
Older IEs don't support explicit binding on host objects though.
You also get this for some native methods which are not generic such as:
var a = function(){}.toString;
a();
TypeError: Function.prototype.toString is not generic
Some are generic:
var fakeArray = {0:1,1:2,length:2};
fakeArray.join = [].join;
fakeArray.join( " " );
"1 2"
Because reload()
needs window.location
as this
. In other words - it is a method of window.location
. When you say:
var fun = window.location.reload;
fun();
You are calling reload()
function without any this
reference (or with implicit window
reference).
This should work:
setTimeout(window.location.reload.bind(window.location), 250);
The window.location.reload.bind(window.location)
part means: take window.location.reload
function and return a function that, when called, will use window.location
as this
reference inside reload()
.
There is another way of doing this, pretty simple, and no need of doing extra steps, bindings or stuff like that. When you use arrow functions instead of common functions in JS, the this
context is included. So you could just as easily do the following:
setTimeout(() => window.location.reload(), 250);