在卸载事件之前使用有什么限制? [英] What are the limitation using before unload event?

查看:17
本文介绍了在卸载事件之前使用有什么限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

beforeunload 回调中可以做什么和不能做什么?

What is and what is not possible to do inside the beforeunload callback ?

是否可以打开 XHR/fetch 并将数据发送到服务器?如果没有,是否可以只发送数据,而没有任何成功回调阻塞?

Is it possible to open an XHR/fetch and send data to the server ? If no, is it possible to just send data, without any success callback blocking ?

是否可以使用 window.location 更改页面的位置?函数继续执行多久?

Is it possible to change the location of the page with window.location? How long does the function continue to execute?

window.addEventListener("beforeunload", function (event) {
    // code
});

推荐答案

你可以在beforeunload"回调中放入任何你想要的东西,你只是不能保证它会执行,除非你使用同步/阻塞代码.

You can put anything you want inside of a "beforeunload" callback, you're just not guaranteed it will execute unless you use synchronous/blocking code.

>

这是我将用于演示目的的阻塞睡眠函数:

Here's a blocking sleep function I'll use for demonstration purposes:

function sleep(delay) {
  var start = new Date().getTime();
  while (new Date().getTime() < start + delay);
}

任何同步的、阻塞的代码都保证执行完成:

Any synchronous, blocking code is guaranteed to execute to completion:

window.addEventListener("beforeunload", function (event) {
  console.log("Blocking for 1 second...");
  sleep(1000);
  console.log("Done!!");
});

任何像下面的代码一样的异步代码(即带有回调的代码)将在事件循环中排队,但它可能会或可能不会完成执行取决于您的浏览器何时完成卸载"操作(例如关闭窗口,刷新页面).) 这里的时间真的取决于您的计算机的性能.例如,在我的计算机上,由于我的浏览器没有时间刷新/关闭页面,因此仍然会执行带有日志语句的 10 毫秒超时.

Any async code (i.e. code with callbacks) like the code below will be queued on the event loop, but it may or may not finish executing depending on when your browser completes the "unload" action (e.g. close window, refresh page.) The time here really depends on your computer's performance. On my computer, for example, a timeout of 10ms with log statement still executes because my browser hasn't had time to refresh/close the page.

window.addEventListener("beforeunload", function (event) {
  setTimeout(() => {
    console.log("Timeout finished!"); // Odds are this will finish
  }, 10);
  console.log("Done!!");
});

然而,100ms 的超时永远不会被执行:

A timeout of 100ms, however, is never executed:

window.addEventListener("beforeunload", function (event) {
  setTimeout(() => {
    console.log("Timeout finished!");
  }, 100);
  console.log("Done!!");
});

确保您的函数运行完成的唯一方法是确保您编写的同步代码会像第一个示例中那样阻塞事件循环.

The only way to guarantee your function will run to completion is to make sure you're writing synchronous code that blocks the event loop as in the first example.

这篇关于在卸载事件之前使用有什么限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆