如果我理解正确的话,似乎所有你想要做的是递归调用的函数,达到一定的次数。这里是一个正是这么做的示例代码:
function testFunction(number, callback) {
document.writeln("testFunction() called with number = " + number + "<br />");
callback(number + 1);
}
var CallCount = 0;
testFunction(1, function(next) {
CallCount++;
document.writeln("callback called next = " + next + "<br />");
if(CallCount == 5) {
document.writeln("callback called 5 times, don't call it again");
} else {
testFunction(next, arguments.callee);
}
});
该代码输出如下:
testFunction() called with number = 1
callback called next = 2
testFunction() called with number = 2
callback called next = 3
testFunction() called with number = 3
callback called next = 4
testFunction() called with number = 4
callback called next = 5
testFunction() called with number = 5
callback called next = 6
callback called 5 times, don't call it again
您可以在jFiddle尝试一下:http://jsfiddle.net/luisperezphd/NQya6/
将此应用于你的代码中得到:
var DebugCount = 0;
function EmulateGetJson(link, callback) {
DebugCount++;
callback({
data: {
children: [
{ data : { url: "https://www.google.com/images/srpr/logo3w.png?" + DebugCount, next: "next" } }
]
}
});
}
function info(link, callback) {
//$.getJSON(link, function(json) {
EmulateGetJson(link, function(json) {
$.each(json.data.children, function(i, things) {
$("#threadlist").append('<img src="' + things.data.url + '">');
});
callback(json.data.after);
});
}
var url_first = "http://www.reddit.com/r/aww/.json?jsonp=?";
var url_part1 = "http://www.reddit.com/r/aww/.json?after=";
var url_part2 = "&jsonp=?";
var CallCount = 0;
var TargetCallCount = 5;
info(url_first, function(next) {
CallCount++;
if(CallCount != TargetCallCount) {
info(url_part1 + next + url_part2, arguments.callee);
}
});
的的jsfiddle为此,可以发现:http://jsfiddle.net/luisperezphd/uY8Kj/
我使用JavaScript代码模拟了$.getJSON
的调用,以提供一个完整的示例。我在示例图像URL的末尾附加了一个数字,以说明每次都返回一个不同的URL。
arguments.callee
指的是当前函数,在这种情况下,您传递的函数作为回调函数info()
这是递归的关键。
这是一个清理的小提琴:http://jsfiddle.net/rdUBD/2/请注意,较慢的电脑可能会遇到加载这些页面的问题。 – 2012-03-11 21:31:09
@JaredFarrish和更快的电脑不会注意到在同步性上的差异:) – vol7ron 2012-03-11 21:39:13