为什么一段时间后我的窗户关闭? (JavaScript)的

时间:2013-11-30 20:33:58

标签: javascript

我无法弄清楚为什么窗户在86秒后不会关闭。

以下是代码:

//Functions 
function URL() {
    return prompt("Enter the URL."); 
} 

function openNewWindow() { 
    var url = URL(); 
    popupWin = window.open(url, 'open_window', 'menubar, toolbar, location, directories, status, scrollbars, resizable,dependent, width=640, height=480, left=0, top=0');
    setTimeout(url,86000); 
} 

//Main
var url1 = openNewWindow(); 

2 个答案:

答案 0 :(得分:2)

一个问题是代码将函数传递给setTimeout,而只是通过prompt读取的字符串。 (虽然setTimeout会接受一个字符串,但由于遗留原因,它必须是有效的JavaScript代码才有意义。)

function URL() {
    return prompt("Enter the URL."); 
} 

function openNewWindow() { 
    var url = URL();   // url is the RETURN VALUE of calling the URL function ..
    popupWin = window.open(url, 'open_window', 'menubar, toolbar, location, directories, status, scrollbars, resizable,dependent, width=640, height=480, left=0, top=0');
    // .. which is a string (representing a URL), not a function
    setTimeout(url,86000); 
} 

与:比较:

function openNewWindow() { 
    var url = URL();   // url is the RETURN VALUE of calling the URL function ..
    var popupWin = window.open(url, 'open_window', 'menubar, toolbar, location, directories, status, scrollbars, resizable,dependent, width=640, height=480, left=0, top=0');
    // .. but we pass a callback function :)
    setTimeout(function () {
        alert("done");
        // And assuming the browser allows this ..
        popupWin.close();
    }, 4 * 1000);
} 

(请注意,我也使popupWin成为var,以便它在闭包中被捕获 - 因此所有打开的窗口应该在它们各自的超时后关闭,而不仅仅是最后一个。)

答案 1 :(得分:-1)

否则该代码中的window.close()被调用。

setTimeout(url, 86000)只需在大约24小时内安排执行url()功能。