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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With