Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass "window.location.reload" as an argument to setTimeout?

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);

Chrome reports:
Uncaught TypeError: Illegal invocation

And Safari:
TypeError: Type error

In FireFox, the code runs fine. Also, this code runs fine in each of the three browsers:

setTimeout((function() {   window.location.reload(); }), 250); 

Chrome and Safari have no issues with this code:

var say_hello = function () { alert("hello") };   setTimeout(say_hello, 250);   

What is special about window.location.reload that causes this error?

(not sure if it's useful or not, but here's a jsfiddle illustrating this)

like image 297
goggin13 Avatar asked May 31 '12 19:05

goggin13


People also ask

Is window location reload deprecated?

Using location. reload() is the valid syntax. It is only the reload with forcedReload which is deprecated. In your case changing location.

Can I use window location reload?

You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.

What does Window location reload false do?

window. location. reload(true); False reloads the page using the version of the page cached by the browser.


2 Answers

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().

See also

  • How can I pass an argument to a function called using setTimeout?
  • Why doesn't console.log work when passed as a parameter to forEach?
  • Preserve 'this' reference in javascript prototype event handler
like image 91
Tomasz Nurkiewicz Avatar answered Sep 28 '22 07:09

Tomasz Nurkiewicz


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); 
like image 45
Javi Marzán Avatar answered Sep 28 '22 05:09

Javi Marzán