繁体   English   中英

如何更改“睡眠”功能以在Internet Explorer中工作?

[英]How do I change the “sleep” function to work in Internet Explorer?

因此,我有一个网站,您可以在其中单击一个按钮,然后将您重定向到另一个页面。 重定向不应立即发生,而应在3秒钟后发生。 为此,我在Stackoverflow上找到了一个可在Chrome和Firefox中完美运行的代码段,但不适用于Internet Explorer。

在Chrome和Firefox上进行了完美的测试。 但是不在Internet Explorer中。

function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function redirect(user) {
        await sleep(500);
        document.getElementById("redirect" + user).innerHTML = "Redirecting.";
        await sleep(700);
        document.getElementById("redirect" + user).innerHTML = "Redirecting..";
        await sleep(700);
        document.getElementById("redirect" + user).innerHTML = "Redirecting...";
        await sleep(700);
        window.open("url", "_newtab");
        await sleep(1000);
        document.getElementById("redirect" + user).innerHTML = "";
    }

一段时间后,应该将我重定向到一个网站。 在Internet Explorer中不起作用。

错误消息:“ Syntaxerror”

哪里?: => return new Promise(resolve => setTimeout(resolve, ms));

您的代码使用了IE11不具备的几个功能:

  • 承诺
  • 箭头功能
  • async / await

要么不使用这些,要么移植到ES5并包含一个promise polyfill。 Babel是您可以使用的一种工具。

在该代码中,“不使用那些”可能只是简单地嵌套setTimeout回调:

setTimeout(function() {
    document.getElementById("redirect" + user).innerHTML = "Redirecting.";
    setTimeout(function() {
        document.getElementById("redirect" + user).innerHTML = "Redirecting..";
        setTimeout(function() {
            document.getElementById("redirect" + user).innerHTML = "Redirecting...";
            setTimeout(function() {
                window.open("url", "_newtab");
                setTimeout(function() {
                    document.getElementById("redirect" + user).innerHTML = "";
                }, 1000);
            }, 700);
        }, 700);
    }, 700);
}, 500);

虽然您也可以使用循环来完成。

您可以看到为什么需要较新的功能。

IE11(2013年发布)不支持async功能(在ES2017中指定),箭头功能或Promises。 使用setTimeout代替:

function makeTimeout(time, user, msg) {
  setTimeout(time, function() {
    document.getElementById("redirect" + user).innerHTML = msg;
  }, time);
}
function redirect(user) {
  makeTimeout(500, user, "Redirecting.");
  makeTimeout(500 + 700, user, "Redirecting..");
  makeTimeout(500 + 700 + 700, user, "Redirecting...");
  setTimeout(function() {
    window.open("url", "_newtab");
  }, 500 + 700 + 700 + 700);
  makeTimeout(500 + 700 + 700 + 700 + 1000, user, '');
}

您可以直接使用setTimeout而不需要Promise

 function redirect(user) { setTimeout(function() { document.getElementById("redirect" + user).innerHTML = "Redirecting."; }, 500); setTimeout(function() { document.getElementById("redirect" + user).innerHTML = "Redirecting.."; }, 1200); setTimeout(function() { document.getElementById("redirect" + user).innerHTML = "Redirecting..."; }, 1900); setTimeout(function() { window.open("url", "_newtab"); }, 2600); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM