簡體   English   中英

在 JavaScript 中同步使用 setTimeout

[英]using setTimeout synchronously in JavaScript

我有以下場景:

setTimeout("alert('this alert is timedout and should be the first');", 5000);
alert("this should be the second one");

我需要在執行setTimeout的代碼后執行setTimeout之后的代碼。 由於setTimeout之后的代碼不是我自己的代碼,我不能把它放在 setTimeout 中調用的函數中......

有沒有辦法解決?

代碼是否包含在函數中?

function test() {
    setTimeout(...);     

    // code that you cannot modify?
}

在這種情況下,您可以阻止該函數進一步執行,然后再次運行它:

function test(flag) {

    if(!flag) {

        setTimeout(function() {

           alert();
           test(true);

        }, 5000);

        return;

    }

    // code that you cannot modify

}

上周我遇到了需要類似功能的情況,這讓我想到了這篇文章。 基本上我認為@AndreKR 所指的“忙等待”在很多情況下都是合適的解決方案。 下面是我用來占用瀏覽器並強制等待條件的代碼。

 function pause(milliseconds) { var dt = new Date(); while ((new Date()) - dt <= milliseconds) { /* Do nothing */ } } document.write("first statement"); alert("first statement"); pause(3000); document.write("<br />3 seconds"); alert("paused for 3 seconds");

請記住,此代碼實際上會阻止您的瀏覽器。 希望它可以幫助任何人。

使用 ES6 & promises & async 你可以實現同步運行。

那么代碼在做什么呢?

 1. Calls setTimeOut 1st inside of demo then put it into the webApi Stack
 2. Creates a promise from the sleep function using the setTimeout, then resolves after the timeout has been completed;
 3. By then, the first setTimeout will reach its timer and execute from webApi stack. 
 4. Then following, the remaining alert will show up.


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

async function demo() {
  setTimeout("alert('this alert is timedout and should be the first');", 5000);
  await sleep(5000);
  alert('this should be the second one');
}
demo();

只需將其放在回調中:

setTimeout(function() {
    alert('this alert is timedout and should be the first');
    alert('this should be the second one');
}, 5000);

不,由於 Javascript 中沒有延遲功能,因此除了忙等待(這會鎖定瀏覽器)之外沒有其他方法可以做到這一點。

ES6(忙等待)

const delay = (ms) => {
  const startPoint = new Date().getTime()
  while (new Date().getTime() - startPoint <= ms) {/* wait */}
}

用法:

delay(1000)
setTimeout(function() {
  yourCode();    // alert('this alert is timedout and should be the first');
  otherCode();   // alert("this should be the second one");
}, 5000);

我認為您必須做出承諾,然后使用 .then() 才能將代碼鏈接在一起。 你應該看看這篇文章https://developers.google.com/web/fundamentals/primers/promises

你可以嘗試用你自己的函數替換 window.setTimeout,就像這樣

window.setTimeout = function(func, timeout) {
    func();
}

這可能會或可能根本無法正常工作。 除此之外,您唯一的選擇是更改原始代碼(您說您不能這樣做)

請記住,像這樣更改本機函數並不是一種非常理想的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM