使用setTimeout返回$ .Deferred()的递归函数

时间:2016-01-06 02:04:29

标签: jquery jquery-deferred

我有一个返回$.Deferred();

的递归函数

功能如下:

var myTest = function (i, deferred) {
    if (!deferred) {
        deferred = $.Deferred();
    }

    if (i < 3) {
        i++;
        console.log("Recursion (" + i + ")!");
        return myTest(i, deferred);
    } else if (i === 3) {
        console.log("Resolving!");
        return deferred.resolve("Woohoo, reached " + i + "!");
    }
}

/* Call it */
myTest(0).done(function (result) {
    console.log(result);
});

这给出了预期的输出:

Recursion (1)!
Recursion (2)!
Recursion (3)!
Resolving!
Woohoo, reached 3!

但如果我将line 8更改为

setTimeout(function() {
    return myTest(i, deferred);
}, 500);

失败了。如何在我的函数中添加超时但实现相同的结果?

JsFiddle original code

JsFiddle with timeout

1 个答案:

答案 0 :(得分:0)

如果我理解你的尝试......

var myTest = function (i) {
  var deferred = $.Deferred();
  
  var interval = setInterval(function(){
    if (i < 3) {
      i++;
      console.log("Iteration (" + i + ")!");
    } else {
      console.log("Resolving!");
      deferred.resolve("Woohoo, reached " + i + "!");
      clearInterval(interval);
    }
  }, 1000);
  
  return deferred;
}

/* Call it */
myTest(0).done(function (result) {
    console.log(result);
});