簡體   English   中英

匿名setTimeout函數

[英]anonymous setTimeout function

我處於等待幾個事件發生的情況。 我看到了許多有關如何使用命名函數使用setTimeout的很好的示例,但是有沒有一種方法可以使用某種匿名方法來進行超時?

該代碼當前看起來像這樣:

testForObject();

function testForObject() {
    if  ( typeof marksObjectName === 'object' )  {
           // blah blah
    } else {
       console.log('marksObjectName does not exist quite yet');
       setTimeout(function() { testForObject() }, 500 );
    }
}

所以我想知道是否有某種方法可以在setTimeout期間命名該函數並使用匿名方法代替,也許是這樣的:

setTimeout(function() {
    if  ( typeof marksObjectName === 'object' )  {
           // blah blah
    } else {
       console.log('marksObjectName does not exist quite yet');
    }
}, 500);

顯然這是行不通的,但這是我的第一個(也是唯一一個)猜測。

非常感謝大家。

您可以命名傳遞的函數,例如

setTimeout(function myFunction() {
    // ...
}, 500);

您可以按以下方式命名該函數。 請注意,您需要將其放置在else子句的另一個超時中:

 setTimeout(function timer() { if (typeof marksObjectName === 'object') { // blah blah } else { console.log('marksObjectName does not exist quite yet'); setTimeout(timer, 500); } }, 500); 

我相信hat setInterval是您想要的。

setInterval(function() { if ( typeof marksObjectName === 'object' ) { // blah blah } else { console.log('marksObjectName does not exist quite yet'); } }, 500);

暫無
暫無

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

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