javascriptloopswhile-looptimingevent-loop

Javascript run loop for specified time


I have a function that interfaces with a telephony program and calls people. I want to know, is there a method that I can use to call folks for a certain amount of time?

I'd like to run a loop like this:

    while (flag = 0) {
        call(people);

        if (<ten minutes have passed>) {
            flag = 1;
        }
    }

Any help would be appreciated.


Solution

  • You probably want the setTimeout() function.

    Something like this should work (untested):

    var keepCalling = true;
    
    setTimeout(function () {
      keepCalling = false;
    }, 60000);
    
    while (keepCalling) {
      // callPeople();
    }
    body {
      height: 100vh;
      margin: 0;
    }
    
    body:hover {
      background: yellow;
    }

    An alternative method if you're having problems with setTimeout():

    var startTime = Date.now();
    
    while ((Date.now() - startTime) < 60000) {
      // callPeople();
    }
    body {
      height: 100vh;
      margin: 0;
    }
    
    body:hover {
      background: yellow;
    }