简体   繁体   English

匿名setTimeout函数

[英]anonymous setTimeout function

i have a situation where i am waiting for a couple of events to happen. 我处于等待几个事件发生的情况。 i see many good examples of how to use the setTimeout using a named function, but is there a way to use some sort of anonymous method for a timeout? 我看到了许多有关如何使用命名函数使用setTimeout的很好的示例,但是有没有一种方法可以使用某种匿名方法来进行超时?

the code currently looks something like this: 该代码当前看起来像这样:

testForObject();

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

so i was wondering if there is some way naming the function during setTimeout and use an anonymous method instead, perhaps something like this: 所以我想知道是否有某种方法可以在setTimeout期间命名该函数并使用匿名方法代替,也许是这样的:

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

obviously this does not work, but it was my first (and only) guess. 显然这是行不通的,但这是我的第一个(也是唯一一个)猜测。

thank you all very much. 非常感谢大家。

You can name the passed function, like 您可以命名传递的函数,例如

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

You can name the function as follows. 您可以按以下方式命名该函数。 Note that you will need to put it within another timeout within the else clause: 请注意,您需要将其放置在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