How to use recursion along with setInterval

How to use recursion along with setInterval

Hi Everyone,

My objective is to

Request a database call

STEP 1: if record is present then display the modal for five seconds

                while closing the modal

again request a database call when the modal closes and repeat (STEP 1:)

STEP2: if no record is present then request a database after every 2 seconds


Below is the code I have tried and various other, but the problem is after the STEP1 is completed for say 4 records after call of these 4 records there is again a database call with all the four records all together and this calls (all 4 ) are repeated which should be only once after 2 seconds


Please help, TIA


$(document).ready(function(){

//the id would be for the Unit ID along with  services of that unit

//var id="<?php echo 1;  ?>";

var id=1;

isopen=$('#myModal').hasClass('in');

if(isopen==true)

{

console.log("MODAL is open");

}

else

{

var mytimer=setInterval(function(){

call_popup(flag="from top call popup");}

,5000); 

console.log("Initalising the time value is"+mytimer); 

}

function call_popup(flag)

{

$.post('<?php echo base_url(); ?>display/get_popup', {id : id}).done(function(datareg) {

var jd=jQuery.parseJSON(datareg);

            //id=0 is returned if there is no record

if(jd.id==0)

{

if ( typeof mytimer !== "undefined" && mytimer) {

      clearInterval(mytimer);


setTimeout(function(){call_popup(flag="calling from settimeout after 3 seconds");}, 3000); 

}

else

{

$("#myid").val(jd.id);

if ( typeof mytimer !== "undefined" && mytimer) {

      clearInterval(mytimer);

}

var id=jd.id;

$("#myModal").modal('show');

//

setTimeout(function() {

$('#myModal').modal('hide');

$('#myModal').on('hidden.bs.modal', function () {call_popup("from recursion");});

}, 5000);

}

});

 }//end of popup function

 

  });