簡體   English   中英

javascript setTimeout()不等待,即使在作為匿名函數調用之后

[英]javascript setTimeout() not waiting, even after calling as an anonymous function

我在使用setTimeout()時遇到問題,它似乎沒有等待調用該函數。 首先,我像這樣使用它:

function function1(driver){
  driver.get(secondaryUrl);
}

driver.get(initialUrl);
setTimeout(function1, 3000, driverInstance);

這沒有用,只是跳過了延遲。 所以我查了一下,顯然包裝了該功能,因為匿名功能可以修復它。 所以我嘗試了這個:

function function1(driver){
  driver.get(secondaryUrl);
}

setTimeout(function(){ function1(driverInstance)}, 3000);

但是,這樣做也一樣,只是跳過延遲並在第一個URL加載后立即導航到第二個URL。 誰能幫我解決問題? 謝謝

從中刪除第三個參數:

setTimeout(function1, 3000, driverInstance);

它應該是:

setTimeout(function () {
    function1(driverInstance)
}, 3000);

我不確定我是否理解正確,因為示例中缺少變量聲明。 我假設您使用某種方法在JS中創建對象。 並且您希望兩次調用此方法,並且之間有一些延遲。 如果是這樣,那么下面的代碼應該可以工作。 我已經將get方法替換為processUrl

var url1 = 'http://something';
var url2 = 'http://another';

function Driver( url ) {
  this.processUrl = function( url ) {
    // some logic with URL
    console.log( url );
  }
}

var driver = new Driver()

driver.processUrl( url1 );

function fun1( instance ) {
  instance.processUrl( url2 )
}

setTimeout(fun1, 3000, driver);

或更簡單的解決方案,而無需使用其他功能:

var url1 = 'http://something';
var url2 = 'http://another';

function Driver( url ) {
  this.processUrl = function( url ) {
    // some logic with URL
    console.log( url );
  }
}

var driver = new Driver()

driver.processUrl( url1 );
setTimeout( driver.processUrl, 3000, url2 );

重要的是:缺少括號() 在函數名稱的末尾添加括號時,將在處理代碼時立即調用函數。 您需要提供參考 ,應在3秒后調用函數。

暫無
暫無

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

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