最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Delay page close with Javascript? - Stack Overflow

programmeradmin3浏览0评论

Now, I understand that it's bad practice to delay a page close, and that there are better ways to handle that kind of stuff, but just for future reference, is there a way to delay the page closing? Something like

window.onunload = unload();

function unload()
{
setTimeout("self.close()", 1000)
}

Thanks!

Now, I understand that it's bad practice to delay a page close, and that there are better ways to handle that kind of stuff, but just for future reference, is there a way to delay the page closing? Something like

window.onunload = unload();

function unload()
{
setTimeout("self.close()", 1000)
}

Thanks!

Share Improve this question edited Dec 31, 2013 at 1:49 elixenide 44.8k16 gold badges78 silver badges100 bronze badges asked Dec 2, 2011 at 0:13 MatthewSotMatthewSot 3,5945 gold badges43 silver badges58 bronze badges 1
  • 2 @GlennSlaven, tried what? The above function doesn't work (of course :P), and I was asking if maybe there was a browser-approved way of doing it, like a function that would delay it for only one second, no more no less, or something – MatthewSot Commented Dec 2, 2011 at 0:22
Add a ment  | 

2 Answers 2

Reset to default 12

If you really need (ie. ready to resort to semi-hacks) to delay the page closing without showing a confirmation dialog, etc, you can do something like the following:

function delay(ms) {
    var start = +new Date;
    while ((+new Date - start) < ms);
}

// start image loading (I assume you need this for tracking?)
delay(150);

The caveats are obvious: it will not always work and you cannot delay for too long. That being said, if you are really interested in this, you can probably get results of over 95% (really depends on the server response time).

onbeforeunload doesn't work with timeout to protect the browser user from being.

The only way to prevent the page from exiting after the user attempts to leave is by putting synchronous code in the onbeforeunload/onunload handler

But there is something you can do!!!

for(var i = 0; i < 2000; i++){
    console.log(i);
}

You can make this for loop printing to console to delay the unload of the page.

The higher number will take delay high to reload page.

发布评论

评论列表(0)

  1. 暂无评论