Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop this setTimeout function from running?

I use the function below to check on the status of a JSON file. It runs every 8 seconds (using setTimeout) to check if the file has changed. Once the JSON's status becomes 'success' I no longer want to keep calling the function. Can someone please show me how to do this? I suspect it involves the use of clearTimeout, but I'm unsure how to implement this.

Cheers!

  $(function() {
    var checkBookStatus = function() {
       var job_id = "#{@job.job_id}";
       var msg = $('.msg');
       var msgBuilding = $('#msg-building');
       var msgQueuing = $('#msg-in-queue');
       var msgSuccessful = $('#msg-successful-build');
       var msgError = $('#msg-error'); 
       $.ajax({ 
         url: '/jobs/'+job_id+'/status.json',

           datatype: 'JSON',
           success:function(data){
             if (data.status == "failure")  {
               msg.hide();          
               msgError.show();
             }
             else if (data.status == "#{Job.queue}")  {
            msg.hide();          
            msgQueuing.show();
         }
             else if (data.status == "#{Job.building}")  {
            msg.hide();          
            msgBuilding.show();
         }             
         else if (data.status == "#{Job.failure}")  {
             msg.hide();          
             msgError.show();
         }
         else if (data.status == "#{Job.success}")  {
             msg.hide();          
             msgSuccessful.show();

              }                    
           },       
       }).always(function () {
            setTimeout(checkBookStatus, 8000);
      });
    };    
   checkBookStatus();    
  });
like image 297
swisstony Avatar asked Dec 06 '22 15:12

swisstony


1 Answers

t = setTimeout(checkBookStatus, 8000); when you decide to stop the timeout use this clearTimeout(t);.

like image 126
Ahmed Jolani Avatar answered Dec 28 '22 18:12

Ahmed Jolani