-2

I have a javascript which checks every 5 seconds if a parent div has 1 child div or more than 1 child div

HTML :

<div id="program-days">
    <div class="row">program 1</div>
    <div class="row">program 2</div>
    <div class="row">program 3</div>
</div>

How I can disable the function below, if #program-days has only 1 child div :

$(document).ready(
function () {
checkProgramData();
checkProgram = setInterval(checkProgramData, checkProgramInterval);
});

Can I use a script something like this? :

setInterval(function(){
if(jQuery('div#program-days .row').length > 1){
    // enable function
    }
else{
    // disable function
    }
}, 1000);
user17092013
  • 11
  • 1
  • 9
  • 4
    Why not try your idea and then report back if you can't get it working? – chevybow May 21 '19 at 14:24
  • 3
    have you tried it ? – Gaël S May 21 '19 at 14:24
  • The approach to this problem is pretty weird. What you probably want to do is always have the function available, and within the function execute code depending on the number of divs. – Joseph Cho May 21 '19 at 14:24
  • Your approach of DOM changing events is not correct. Take this question as guide https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom – pbibergal May 21 '19 at 14:27

2 Answers2

0

Just give your interval a variable name:

var programDaysInterval = setInterval(...);

In the else of your function you can stop the interval by it's name:

clearInterval(programDaysInterval);

Complete example:

$(function() {
    function checkProgram() {
        if($("#program-days").find('.row').length > 1) {
            console.log('stop');
            clearInterval(checkProgramInterval);
        } else {
            console.log('just keep going');
        }
    }

    var checkProgramInterval = setInterval(checkProgram,500);
});
Sjoerd Loeve
  • 231
  • 1
  • 5
0

You don't need Jquery for this. This is a possible solution:

The first one is a basic if else statement, the other one stops the interval whenever there is less than 1 row. Was this the answer you were looking for?

//Basic solution
setInterval(() => {
 if(document.querySelectorAll('#program-days > .row').length > 1){
  
  }else{
   
  }
},1000)

// Stopping interval / function if not true
let interval = setInterval(() => {
 if(document.querySelectorAll('#program-days > .row').length > 1){
   
  }else{
   interval.clearInterval()
  }
},1000)
<div id="program-days">
    <div class="row">program 1</div>
    <div class="row">program 2</div>
    <div class="row">program 3</div>
</div>