nutzt
nutzt

Reputation: 2923

JavaScript multiple intervals and clearInterval

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...

Upvotes: 3

Views: 6801

Answers (2)

zzjyingzi17
zzjyingzi17

Reputation: 1

maybe you can try like this.

var loopLockingVar;

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

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

  // code
});

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

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]);
    }
});

Upvotes: 8

Related Questions