0

I have the following code :

function job(job_id){
    $( "#demo" ).append("Next" + job_id);
  setInterval(job, 1000, 1);
  
}
job(1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div id="demo">

</div>

Why the function doesn't wait 1 second before being executed ?

My goal is to use it in a function which contain an ajax call.

function job(job_id){
    $.ajax({
        type: "POST",
        url: "data/job.php",
        data: { 'job_id' : job_id },
        dataType: 'json',
        success: function(data){
            $.each(data, function(index, element) {
                if(index == 'status'){
                    if(element == "Terminated"){
                        $("#cronExecutebtn").prop("disabled",false).html("Sync")
                        console.log('stop')
                        clearInterval(myInterval);
                    }else if(element == "In progress"){
                        console.log('continu');
                        job(1)
                        //const myInterval = setInterval(job(1), 1000);
                        //const myInterval = setInterval(job, 1000, 1);
                        //setInterval(job(job_id), 1000);
                        //const myTimeout = setTimeout(job(job_id), 5000);
                    }                                       
                }
            });
        }
    });
}
                   
const myInterval = setInterval(job, 1000, 1);

The goal is, when element is equal to "In progress", wait 1 second and re run the function to check the status, if the status is equal to "Terminated" then stop.

executable
  • 3,365
  • 6
  • 24
  • 52
  • The problem is because you're executing `job(1)` immediately and providing *the output* of that function to the `setInterval()`. You instead need to wrap that function invocation in another anonymous function. See the duplicate for more information, specifically this answer: https://stackoverflow.com/a/54190603/519413 – Rory McCrossan Aug 04 '22 at 07:59
  • As a side note, making an AJAX request to your server every 1 second is not a good idea. It doesn't scale and will DDOS your own server. I'd strongly suggest using sockets if you need to keep the UI and server data in close synchronicity. – Rory McCrossan Aug 04 '22 at 08:00
  • 1
    You should use, `setTimeout` instead as you are calling the function recursively. – Abhay Srivastav Aug 04 '22 at 08:03
  • 1
    As above, when you use `setInterval` inside the interval, it adds another timer each time. User `setInterval` outside the timer or `setTimeout` inside. – freedomn-m Aug 04 '22 at 08:31

0 Answers0