Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...