JavaScript multiple intervals and clearInterval

2019-07-24 22:50发布

问题:

I have a small program, when you click on an "entry", the editing mode is opened, and the entry is to edit locked for others. There is every 10 seconds sends an ajax request to update the timestamp in the table.

$(".entry-edit").click(function() {
  // code

  loopLockingVar = setInterval(function() { loopLockingFunction(id) }, 10000);

  // code
});

Then I have a cancel button to updating the timestamp in the table to 0 and to clear the interval.

$(".entry-cancel").click(function() {
  // code   

  clearInterval(loopLockingVar);

  // code
});

It all works when editing only one entry, but if two or more processed simultaneously, and then click cancel, the interval for the first entry still further...

I have this tried:

var loopLockingVar;
$(".entry-edit").click(function() {
  // code

  if( ! loopLockingVar) {
    loopLockingVar = setInterval(function() { loopLockingFunction(id) }, 10000);
  }

  // code
});

However, this does not work more if you cancel and again clicks on edit...

回答1:

You're assigning multiple interval IDs to the same variable which will only hold the interval ID that was assigned to it last. When you clear the interval, only the interval corresponding to that ID will be cleared.

A straightforward solution would be to maintain an array of interval IDs, and then clear all intervals represented in the array. The code could look something like this:

var intervalIds = [];

$(".entry-edit").click(function() {
    intervalIds.push(setInterval(function() { loopLockingFunction(id) }, 10000));
});

$(".entry-cancel").click(function() {
    for (var i=0; i < intervalIds.length; i++) {
        clearInterval(intervalIds[i]);
    }
});


回答2:

maybe you can try like this.

var loopLockingVar;

$(".entry-edit").click(loopLockingVar,function() {
  // code

    loopLockingVar = setInterval(function() { loopLockingFunction(id) }, 10000);

  // code
});