SetInterval() with "if" condition in js function

Viewed 14149

I would like to continuously call the function below using setInterval() but only if the condition in the if statement evaluates to true. Note: The function is global.

function view_stack(){
    if(my_stack.size() > 0){
        document.getElementById("stack_visual").innerHTML = my_stack.view();
    } else {
        swal("Ohhhh Noes", "There are no items in the stack!", "error");
    }
}      

Is there a way I can achieve it?

3 Answers

Make it so that your function does nothing when there is nothing to do. That way you can simply keep the interval running.

Effectively your code already is written like that, I would rearrange it like this:

function view_stack(){
    if(my_stack.size() === 0) return;
    document.getElementById("stack_visual").innerHTML = my_stack.view();
}

setInterval(view_stack, 1000);

The more elegant solution would be event-based, i.e. whenever my_stack changes, update the view.

You could put an if statement in the setInterval function like so:

setInterval(function() {
  if(my_stack.size() > 0) {
    view_stack();
  }
}, 1000/60);

So, only if my_stack.size() > 0 it will then call the view_stack() function.

Note setInterval() is triggered 60 times per second.

You can simply nest your function within a setTimeout nested within a while loop.

function view_stack(){

  while(my_stack.size() > 0){
  
    setTimeout(() => {
    
      document.getElementById("stack_visual").innerHTML = my_stack.view();
    
    ), 1000} //for a second rhythm.
  
  }
  
  swal("Ohhhh Noes", "There are no items in the stack!", "error");

}

this way the function will work only if "true" and still have control over the rhythm it works.

Related