Delayed Centered Popup Javascript using setTimeout
-
22-06-2021 - |
Frage
Trying to get a centered popup to display after a set value of time, something like this:
<script type="text/javascript">
<!--
function popup(url) {
var width = 300;
var height = 200;
var left = (screen.width - width) / 2;
var top = (screen.height - height) / 2;
var params = 'width=' + width + ', height=' + height;
params += ', top=' + top + ', left=' + left;
params += ', directories=no';
params += ', location=no';
params += ', menubar=no';
params += ', resizable=no';
params += ', scrollbars=no';
params += ', status=no';
params += ', toolbar=no';
newwin = window.open(url, 'windowname5', params);
if (window.focus) {
newwin.focus()
}
setTimeout(popup('`test/login.html'), 5000);
return false;
}
//-->
//]]>
</script>
but the popup never displays. If I write it like this:
<script type="text/javascript">
<!--
function popup(url) {
var width = 300;
var height = 200;
var left = (screen.width - width) / 2;
var top = (screen.height - height) / 2;
var params = 'width=' + width + ', height=' + height;
params += ', top=' + top + ', left=' + left;
params += ', directories=no';
params += ', location=no';
params += ', menubar=no';
params += ', resizable=no';
params += ', scrollbars=no';
params += ', status=no';
params += ', toolbar=no';
newwin = window.open(url, 'windowname5', params);
if (window.focus) {
newwin.focus()
}
return false;
}
setTimeout(popup('`test/login.html'), 5000);
//-->
//]]>
</script>
the popup displays immediately, but then I receve an Invalid Argument error. Suggestions?
Lösung
setTimout
takes a function as its first parameter. popup(...)
does not return a function. Try this:
setTimeout(function() {popup('`test/login.html');}, 5000)
Andere Tipps
In your first example, you placed the setTimeout
within the body of the popup()
function. The body of that function won't be run until the function is called. So, you're right in your second attempt to place the setTimeout
outside of the popup()
body.
The other problem is that you need to pass either a function or code to setTimeout()
:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
var timeoutID = window.setTimeout(code, delay);
Like so:
setTimeout(function() {
popup('`test/login.html'); // provided that tick-mark is right...
}, 5000);
Whereas your existing method will execute popup()
immediately and provide no function to the timout function:
setTimeout(popup('`test/login.html'), 5000);