根据时间设置超时不运行功能

时间:2016-08-24 08:25:38

标签: knockout.js

我正在使用settimeout来运行该函数,每10秒钟一次,它会达到60秒并退出,由于某种原因它不会经过设置超时并退出该过程。

self.startInstatorCheck = function() {
  self.instatorStarts(true);
  var MAX_WAIT_TIME_MS = 1 * 60 * 1000;
  var POST_INTERVAL_MS = 10 * 1000;
  var timeout = Date.now() + MAX_WAIT_TIME_MS;

  self.proceedInstantorcheck(POST_INTERVAL_MS, timeout);
}

self.proceedInstantorcheck = function(POST_INTERVAL_MS, timeout) {
  debugger;
  var date = Date.now();
  $.ajax({
      type: 'POST',
      url: BASEURL + 'index.php/moneyexchange/check_instantor_field/' + auth,
      contentType: 'application/json; charset=utf-8'
    })
    .done(function(userinfo) {
      if (userinfo.instantor_request > 12) {
        return self.allInstantorCheckMessages('Instantor data gathered');
      } else {
        if (date < timeout) {
          /* setTimeout just moves forward and does not repeat*/
          setTimeout(self.proceedInstantorcheck(), POST_INTERVAL_MS);
        } else {
          self.allInstantorCheckMessages('Please go through instantor to ');
          self.instatorStarts(true);
          self.magicInstantorbtn2(true);
        }
      }
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
      self.errorMessage(errorThrown);
    })
    .always(function(data) {

    });
}

我使用两个函数,因为第一个获取数据,第二个函数重新运行而不是每次都获得新的超时值。

2 个答案:

答案 0 :(得分:2)

您没有正确使用setTimeout。它的第一个参数是function。如果此函数需要参数,则必须使用.bind或通过包装其他方法传递它们。这是一个有效的例子(注意我已经嘲笑了ajax部分并减少了间隔和超时时间)。

注意:

  • 运行代码段查看是否有效。
  • 此代码不会保护您不会同时运行多个startCheck。确保你只打电话一次!
  • 模拟的ajax代码的固定超时为500毫秒,因此proceedCheck每1000毫秒(POST_INTERVAL_MS)+ 500毫秒= 1500毫秒调用。由于我们在6000毫秒后停止重试,我们得到5次尝试:
    • 尝试1:0ms,
    • 尝试2:500毫秒,
    • 尝试3:2000ms,
    • 尝试4:3500ms,
    • 尝试5:5000毫秒
    • 尝试6:6500ms

&#13;
&#13;
// Mock jQuery ajax, do not include 
var $ = {
  ajax: function(opts) {
    return {
      done: function(cb) {
        setTimeout(cb.bind(null, {
          "instantor_request": 10
        }), 500);
      }
    };
  }
}, i = 0;

// The logic:
var startCheck = function() {
  var MAX_WAIT_TIME_MS = 1 * 6 * 1000;
  var POST_INTERVAL_MS = 1 * 1000;
  var timeout = Date.now() + MAX_WAIT_TIME_MS;

  proceedCheck(POST_INTERVAL_MS, timeout);
};

var proceedCheck = function(interval, limit) {
  console.log("Check " + i++);
  $.ajax({})
    .done(function(userinfo) {
      if (userinfo.instantor_request > 12) {
        console.log("Valid request");
      } else {
        if (Date.now() < limit) {
          setTimeout(function() {
            proceedCheck(interval, limit);
          }, interval);
        } else {
          console.log("Request timed out");
        }
      }
    })
}

startCheck();
&#13;
&#13;
&#13;

答案 1 :(得分:1)

setTimeout获取一个指向函数的指针,不应该传递调用该​​函数的结果。

setTimeout(self.proceedInstantorcheck(), POST_INTERVAL_MS);

应该是

setTimeout(self.proceedInstantorcheck, POST_INTERVAL_MS);