如何安全地从setTimeout回调中的数组中删除项目

时间:2016-02-02 03:47:56

标签: javascript timer race-condition

我有一个接收对象和可选的到期时间的函数,为该对象分配一个唯一的id并将其插入到数组中。如果提供了到期时间,则设置超时回调,该回调通过其唯一ID查找数组中的对象并将其删除。

  var lastId = 0;
  var messages = [];

  function add(messageObj, expiryTime) {
    var newId = ++lastId;
    messageObj['_id'] = newId;
    messages.push(messageObj);

    if (expiryTime) {

      // find message object to remove
      setTimeout(function() {
        var index = null;
        for (var i = 0; i < messages.length; i++) {
          if (messages[i]['_id'] == newId) {
            index = i;
            break;
          }
        }

        // at this point, if another callback removes an item from the array, then we have a race condition
        messages.splice(index, 1);
      }, expiryTime);
    }
  }

现在,我的问题是:这里有没有竞争条件(如果有的话,如何处理它),或者在javascript计时器中做这种事情是否安全?

0 个答案:

没有答案