-2

Thanks for the attention, and sorry form my very bad english.

I have a nice function using jQuery:

function(){
    //do something
    if(certain conditions){
        return true;
    }else{
        return false;
    }
}

The function work nice... But I need to execute it every X seconds, while the function returns false. If the function returns true, the loop must be stopped.

I have not idea how to do that... Can you help me? Thanks in advance...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Matt Ross
  • 67
  • 7

3 Answers3

1

you could use an setInterval combined with clearInterval.

var interval = setInterval(function(){
    if(certain conditions)
    {
        // this will prevent the function from running again
        clearInterval(interval); 
        return true;
    }

    return false;
},1000); // 1000 ms or, 1 sec
phishfordead
  • 377
  • 2
  • 7
  • And how the unknown logic (which is badly described from the OP's question) will use the returned value? – Ele Apr 06 '18 at 19:29
  • 1
    @Ele that's a great question. He didn't actually say he needed to use the returned value, just that the function had to stop being called when it would return true. – phishfordead Apr 06 '18 at 19:34
  • 1
    @Ele, also, it's not my responsibility to show him how to use a return value. What would I do, instead of returning the value I would set some variable to either true or false, then check that variable. – phishfordead Apr 06 '18 at 19:35
1

You can always use the good old window.setInterval():

var interval = 500;
function callback(){
  //your function call here
  var result = yourFunction();
  //check if we need to clear the timeout
  if(result == true){
      clearTimeout(handle);
  }
}
var handle = setInterval(callback, interval)

Here's a snippet.

var interval = 500;
function callback(){
 //your function call here
  var result = yourFunction();
  //check if we need to clear the timeout
  if(result == true){
    clearTimeout(handle);
  }
}
var handle = setInterval(callback, interval)

function yourFunction(){
  document.write(new Date().toLocaleTimeString())
  if(Math.random() > 0.2){return false}
  else return true;
}
Roope
  • 291
  • 1
  • 8
-1

You are looking for the window.setTimeout function.

function yourFunction(){
    // do your task
    if(1 == 1 /* the condition to make the loop continue*/){
        return true;
    }else{
        return false;
    }
}

function loop(){

  if(yourFunction()){
      window.setTimeout(loop, 1000);
  }
}

loop();
John Caprez
  • 393
  • 2
  • 10