Skip to content

Instantly share code, notes, and snippets.

@ZhangYiJiang
Created January 25, 2011 07:06
Show Gist options
  • Save ZhangYiJiang/794606 to your computer and use it in GitHub Desktop.
Save ZhangYiJiang/794606 to your computer and use it in GitHub Desktop.
Lightweight SE API Wrapper
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment