skip to Main Content

How can I use the clearInterval the function when function meets some condition?

Code:-

var checkRecordlock = function() {
  jQuery.ajax({
    url: "http://localhost/project/crl/Mzk="
  }).done(function(data) {
    var is_locked = data.locked;
    if (is_locked == 1) {
      alert("Locked");
    }
  });
}

checkRecordlock();
var checkRecordlockIntervalId = setInterval(checkRecordlock, 100);

I want to clear the interval of the function if is_locked == 1.

2

Answers


  1. checkRecordlock();
    var checkRecordlockIntervalId = setInterval(checkRecordlock, 100);
    
    function checkRecordlock() {
      jQuery.ajax({
        url: "http://localhost/project/crl/Mzk="
      }).done(function(data) {
        var is_locked = data.locked;
        if (is_locked == 1) {
          clearInterval(checkRecordlockIntervalId);
        }
      });
    }
    
    Login or Signup to reply.
  2. You don’t need to call checkRecordlock before the interval. In order to stop it when the condition reaches, use clearInterval and pass it checkRecordlockIntervalId. Here is an example:

    var checkRecordlock = function() {
        is_locked++;
        console.log(is_locked);
        if (is_locked == 10) {
          alert("Locked");
          clearInterval(checkRecordlockIntervalId)
        }
    }
    let is_locked = 0;
    //checkRecordlock();
    var checkRecordlockIntervalId = setInterval(checkRecordlock, 100);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search