user977101
user977101

Reputation: 161

clear one timeout, start another

I'm auto-refreshing the content on a site using ajax/json. Using jkey, I trigger some posting to the document, and during this action I want to cancel the original setTimeout that's running ("reloading" at 2 mins) - and then trigger the entire function "content" again to start over after 5 secs. However, I can't seem to stop "reloading" properly, neither call "content" after the given seconds. Can anybody spot the error?

 <script>
$(function content(){
  function reloading(){
      $.ajax({                                      
      url: 'api.php',                          
      data: "",                      
      dataType: 'json',                    
      success: function(data)          
      {
        var id = data[0];              
          _id = id;
        var vname = data[1];           
        var message = data[2]; 
        var timestamp = data[3]; 
        var field1 = data[4]; 
        _field1 = field1;
        var val2 = parseInt(field1, 10) ;
        _val2 = val2;
        $('#output').hide().html( message ).fadeIn("slow");   
         $('#username').hide().html( vname +":" ).fadeIn("slow");
      setTimeout(reloading,120000);
 }
      });
  }
  reloading();
}); 

  $(document).jkey('a',function() {
     $.post("update.php", { "id": _id} )
      $('#output').hide().html( "<i>thx" ).fadeIn("slow");
      $('#username').fadeOut("fast");
      $('#valg1').fadeOut("fast");
      $('#valg2').fadeOut("fast");
        clearTimeout(reloading);
       setTimeout(content,5000);
      });
</script>

Upvotes: 3

Views: 1499

Answers (3)

bennedich
bennedich

Reputation: 12377

Besides saving the timeout id as mentioned in other posts, your function reloading is created inside function content and since you create no closure to it, it's unreachable from the rest of the program.

$(function content(){
    function reloading(){
        console.log('RELOADING');
    }
    reloading();
}); 

// Can't reach `content` or `reloading` from here

You have to do something like this:

var reloading, content, reloadingTimeoutId, contentTimeoutId;


reloading = function () {
    console.log('RELOADING');
    $.ajax(
       // CODE
       success : function (data) {
           // CODE
           reloadingTimeoutId = setTimeout(reloading, 120000);
       }
    )
};


content = function () {
    reloading();
};


$(document).jkey('a',function() {
    // CODE
    clearTimeout(contentTimeoutId);
    contentTimeoutId = setTimeout(content,5000);
});

It's kinda difficult writing this better not knowing the bigger picture. With this, content will be called after 5 seconds and as long as reloading succeeds it will callback itself every 120 seconds. Please observe that reloading is never cleared this way.

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66389

The clearTimeout should get the unique "key" that is returned by setTimeout. So when setting, assign the return value to global variable:

window["reload_timer"] = setTimeout(reloading,120000);

Then have this:

clearTimeout(window["reload_timer"]);

Upvotes: 3

MeLight
MeLight

Reputation: 5565

You must save the setTimeout() id in order to later clear it with clearTimeout(). Like this:

var timeoutID = setTimeout(function(){someFunction()}, 5000);//this will set time out
//do stuff here ...
clearTimeout(timeoutID);//this will clear the timeout - you must pass the timeoutID

Upvotes: 3

Related Questions