我不知道如何在NodeJS中使用setTimeOut函数。我想说:
请问你如何在Node.js中做到这一点!
答案 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();