gist: Lightweight SE API Wrapper, 2011-01-25 07:06:46Z
var apikey = 'xxxxxxxxxxxxxxxx',
apiPrefix = 'http://api.stackoverflow.com/1.0/';
if(!Date.now) {
Date.now = function () {
return +new Date();
};
}
var api = {
_stack: [],
_running: false,
_lastCallTime: 0,
_next: function () {
var nextData = this._stack.shift();
if(nextData) {
$.ajax({
url: apiPrefix + nextData.route,
dataType: 'jsonp',
jsonp: 'jsonp',
data: $.extend(nextData.data, {
api: apikey
}),
cache: true,
context: nextData,
success: function(data){
this.callback(data);
if(this.totalPage === data.page) {
this.last(data);
} else if(data.total - (data.page * 100) > 0) {
if(Date.now - this._lastCallTime < 200) {
setTimeout(api._next, 200);
} else {
api._next();
}
}
}
});
} else {
this._running = false;
}
},
add: function (route, data, count, callback, afterLast){
var pageCount = ~~(count / 100),
lastOffset = (count % 100);
if(lastOffset === 0) pageCount--;
for(var i = 0; i < pageCount + 1; i++) {
this._stack.push({
'route': route,
'data': $.extend({
page: i + 1,
pageSize: ((i === pageCount) ? lastOffset : 100)
}, data),
'callback': callback,
'last': afterLast,
'totalPage': (pageCount + 1)
});
}
if(!this._running) {
this._next();
}
}
}