0

is it possible in jScript to do something like the following using multiple anonymous setTimeout functions?

var eventCounter;

// wait for eventCounter to be equal to 1
console.log('eventCounter is now equal to one');

// pause for eventCounter to be equal to 2
console.log('eventCounter is now equal to two');

// finally, wait for eventCounter to be equal to 3
console.log('eventCounter is now equal to three');

I had hoped something like this might have worked:

setTimeout( () =>  {                 // fake code
   if  ( eventCounter <= 1234 ) {    
        this();                      // fake code, this() is not a function
   } else {
       console.log('eventCounter is now over 1234');
   }
}, 200);

or maybe Promises is the way to go?

otherwise it seems like i end up with some sort of deeply embedded nested perform loop with multiple function names, which i had hoped to avoid.

thank you very much.

edwardsmarkf
  • 1,387
  • 2
  • 16
  • 31
  • 1
    You may want to look into promises and the `async`/`await` syntax. The latter is standardized but not yet implemented in most JavaScript engines (node.js, browsers etc.), but you can run your code through Babel (among others) to transform `async`/`await` into browser-supported code. – Frxstrem Mar 10 '17 at 00:04
  • Are you just trying to get a tick to go off every second? – Raydot Mar 10 '17 at 00:05
  • What is `eventCounter`? Who increments it? – Bergi Mar 10 '17 at 02:49
  • If you want a recursive polling loop, just use a named function that you can call. – Bergi Mar 10 '17 at 02:50
  • "eventCounter" is something i just made up, and a server-process will control this value. it appears there is no way to do any of this without using functions, or wrap my tired old brain around Promises. – edwardsmarkf Mar 10 '17 at 03:54

1 Answers1

0

I found this on SO, but unfortunately i am unable to remember where i found it:

var waitValue = false;
var counter = 0;
(function tester() {
   if  ( waitValue ) {
      console.log('finally true');
   } else {
       if  ( counter > 1000 ) {
           console.log('waited too long');
           process.exit;
       } else {
           console.log('still waiting, counter = ' + counter++);
           setTimeout(tester, 1000);
       }
   }
})();
// wait a few seconds and enter this into the console:
var waitValue = false;

and another perhaps better excellent idea was suggested here:

    (function loop(counter) {
        if ( waitValue )  {
            console.log('waitValue is now true');
            resolve('FIRST PROMISE');
        } else if  ( counter <= 0 ) {   // dont wait forever.
            reject('waited too long');
        } else {
            console.log('Count down: ' + counter);
            setTimeout( loop.bind(null, counter-1), 3000);
        }
    })(counter); // initial value of count-down
Community
  • 1
  • 1
edwardsmarkf
  • 1,387
  • 2
  • 16
  • 31