JavaScript multiple intervals and clearInterval

 ̄綄美尐妖づ 提交于 2019-12-24 03:17:20

问题


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


来源:https://stackoverflow.com/questions/27144619/javascript-multiple-intervals-and-clearinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!