Nodejs setTimeOut函数

时间:2014-04-04 06:22:14

标签: javascript node.js settimeout setinterval

我不知道如何在NodeJS中使用setTimeOut函数。我想说:

  1. 每隔10秒调用一次函数A()。
  2. 如果函数A返回值回调结果' true',它将调用一个URL并完成!
  3. 如果函数A保持返回值回调结果' false',请保持通话直到收到“是”' 10分钟
  4. 如果它达到最多10分钟并且仍然没有'真实'结果,最后返回' false'
  5. 请问你如何在Node.js中做到这一点!

3 个答案:

答案 0 :(得分:0)

简单示例(可能需要调整)

var timed_out = false,
    timer     = setTimeout(function() {
        timed_out = true;
    }, (1000*60*10)); // ten minutes passed


function A() {
    call_func(function(result) { // call func with callback
        if (result) {
             clearTimeout(timer);
             DONE();
        }else if (! timed_out ) {
            setTimeout(A, 10000); // call again in 10 seconds
        }
    });
}

答案 1 :(得分:0)

var tenMinutes = false; // my boolean to test the 10 minutes
setTimeout(function() { tenMinutes = true; }, 600000); // a timeout to set the boolean to true when the ten minutes are gone

function A() {
    $.ajax({
        url: "myURL",
        method: "POST",
        data: {},
        success: function(myBool) {
            if (!myBool && !tenMinutes) { // if false, and not ten minutes yet, try again in ten seconds
                setTimeout(A, 10000);
            }
            else if (!myBool && tenMinutes) { // else, if still false, but already passed ten minutes, calls the fail function (simulates the return false)
                myFailresponse();
            }
            else { // if the AJAX response is true, calls the success function (simulates the return true)
                mySuccessResponse();
            }
        }
    });
}

function mySuccessResponse() {
    // you've got a "return true" from your AJAX, do stuff 
}

function myFailResponse() {
    // you've lots of "return false" from your AJAX for 10 minutes, do stuff 
}

A(); // call the A function for the first time

答案 2 :(得分:0)

这是另一种方法。您可以使用setInterval定期调用该函数。如果您获得成功,请做成功并取消计时器。否则,只需取消达到限制的时间。

function a(){
  console.log('a called');
  return false;
}

var doThing = (function() {
    var start,
        timeout,
        delay = 1000,  // 1 second for testing
        limit = 10000; // 10 seconds for testing
    return function() {

      if (!start) {
        start = new Date().getTime();
        timeout = setInterval(doThing, delay);
      } 

      // Call a and tests return value
      if (a()) {

        // Do success stuff

        // Set start to 0 so timer is cancelled
        start = 0;
      }

      // stop timer if limit exceeded or start set to zero
      if ( new Date().getTime() > start + limit || !start) {
        timeout && clearTimeout(timeout);
        timeout = null;
        start = null;
      }
  } 
}());

doThing();