edwardsmarkf
edwardsmarkf

Reputation: 1417

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?

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(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.

Upvotes: 0

Views: 68

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

You can name the function as follows. Note that you will need to put it within another timeout within the else clause:

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

Upvotes: 1

Leonardo
Leonardo

Reputation: 314

You can name the passed function, like

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

Upvotes: 1

Diego ZoracKy
Diego ZoracKy

Reputation: 2285

I believe hat setInterval is what you are looking for.

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

Upvotes: 0

Related Questions