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

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

问题描述

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

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

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

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 ?

是否可以使用<$ c来更改页面的位置$ c> 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!!");
});

任何异步代码(例如带有回调的代码),例如下面的代码,都会在事件循环中排队,但它可能会或可能不会完成执行,具体取决于您的浏览器何时完成卸载操作(例如,关闭窗口,刷新页面。)此处的时间实际上取决于计算机的性能。例如,在我的计算机上,由于我的浏览器没有时间刷新/关闭页面,仍然执行带日志语句的10ms超时。

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天全站免登陆