lundi 23 octobre 2017

Can not stop the function running on setTimeout

I have the following javascript function that runs every 10 seconds to sync some data with the database.

function sync(){
  latestID = $("#dataDiv tbody tr:first").attr("data-key");
  var url = '<?=$model['fn']?>';
  $.ajax({
    url: url,
    type: 'post',
    dataType: 'json',
    data:{latestID: latestID},
    success: function (result) {
      //Do some stuff
    }
  });
  setTimeout(sync, 10000);
}

This function starts to execute when a Activate Sync checkbox is checked. but once it is running, it does not stop when unckecking the checkbox. Below is what I already have tried that does do anything and the function gets executing until the page is reloaded (the checkbox is unchecked by default)

function checkSync(){
  var doSync;

  if($('#keepChecking').is(':checked')){
    doSync = sync();
    //alert("checked"); return false;
  }else{
    clearTimeout(doSync);
    return false;
    //alert("not checked"); return false;
  }
}




Aucun commentaire:

Enregistrer un commentaire