Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetInterval() with "if" condition in js function

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?

like image 824
Phillip Musumba Avatar asked Nov 20 '25 09:11

Phillip Musumba


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

like image 108
Tomalak Avatar answered Nov 23 '25 00:11

Tomalak


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.

like image 23
Nick Parsons Avatar answered Nov 22 '25 23:11

Nick Parsons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!