Reputation: 484
I have a function that is repeated every 3 seconds like this:
function myFunction() {
// Do something sexy
var delay = 3000;
setTimeout(function() {
myFunction();
}, delay);
}
It's running inside a Bootstrap modal window and it should only run when that window is open.
I tried wrapping the delay into a something like:
if ($('#modal-task').hasClass('in')){
var delay = 3000;
setTimeout(function() {
myFunction();
}, delay);
}
But the problem is then if the modal is closed and re-opened, the function runs twice and more times each time it's closed and opened.
How do I kill the function completely when the modal is closed/invisible?
Upvotes: 0
Views: 195
Reputation: 3006
When you close the Bootstrap model 'in' will remove from model class. So when close the model clear the timeout It will work.
like.
function myFunction() {
// Do something sexy
console.log("test");
var delay = 3000;
//Assign setTimeout in variable timerval
let timerval = setTimeout(function() {
myFunction();
}, delay);
//when close the model clear the timeout
if (!$('.#modal-task').hasClass("in")){
clearTimeout(timerval );
}
}
Upvotes: 0
Reputation: 176
this might work, instead of if statement
function something_sexy () {
// Do something sexy
var delay = 3000;
setTimeout(function() {
myFunction();
}, delay);
}
while ($('#modal-task').hasClass('in')) {
something_sexy();
}
Upvotes: 1