Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  22] [ 6]  / answers: 1 / hits: 16572  / 7 Years ago, sun, october 8, 2017, 12:00:00

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?


More From » jquery

 Answers
7

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.


[#56290] Tuesday, October 3, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
georginat

Total Points: 656
Total Questions: 107
Total Answers: 108

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;