簡體   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