JavaScript 多个间隔和 clearInterval [英] JavaScript multiple intervals and clearInterval

查看:67
本文介绍了JavaScript 多个间隔和 clearInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小程序,当你点击一个条目"时,打开了编辑模式,该条目是编辑锁定给其他人.每 10 秒发送一个 ajax 请求来更新表中的时间戳.

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

然后我有一个取消按钮来将表中的时间戳更新为 0 并清除间隔.

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

我试过了:

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

推荐答案

您将多个区间 ID 分配给同一个变量,该变量将只保存最后分配给它的区间 ID.清除区间时,只会清除该ID对应的区间.

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.

一个简单的解决方案是维护一个区间 ID 数组,然后清除数组中表示的所有区间.代码可能如下所示:

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

这篇关于JavaScript 多个间隔和 clearInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆