Skip to content

Instantly share code, notes, and snippets.

@5509
Created April 8, 2011 04:23
Show Gist options
  • Save 5509/909281 to your computer and use it in GitHub Desktop.
Save 5509/909281 to your computer and use it in GitHub Desktop.
キューの仕組みを理解するために書いた。つまり車輪のなんたら。キューの管理配列と実行中フラグがprototypeに入ってしまってたので個別に
/*
* Queue
*
* @author : nori(norimanai@gmail.com)
* @copyright : 5509(http://5509.me/)
* @license : The MIT License
* @modified : 2011-04-08 13:22
*/
// 汎用キューコンストラクタ
function Queue() {
// キューの管理
this.queue: [];
// 実行中監視フラグ
this.running: false;
}
Queue.prototype = {
// キューに登録
// funcは省略可
add: function() { // (func, wait) or (wait)
var _a = arguments;
// waitの指定がない場合は即時(10ms)実行
if ( typeof _a[0] !== "function" ) {
this.queue.push(_a[0] || 10);
} else {
this.queue.push([_a[0], _a[1] || 10]);
}
},
// 登録されたキューを全て削除
clear: function() {
this.running = false;
this.queue = [];
},
// 登録されたキューを先頭から実行する
flush: function() {
var _this = this,
_thisQueue;
// flushの実行は一度だけ
if ( this.running ) return false;
this.running = true;
// キューの先頭にある関数を実行し(ない場合は何もしない)
// waitミリセカンド後に次のキューへ移る
// 実行したら次のキューの処理へ
(function() {
var _thisWait;
// キューが残っていなければ処理を中断する
if ( _this.queue.length === 0 ) {
// there is no queue
_this.running = false;
return false;
}
_thisQueue = _this.queue[0];
// 先頭のキューを削除して詰める
_this.queue.splice(0, 1);
// 現在のキューに登録されている関数を実行
if ( typeof _thisQueue === "object" ) {
_thisQueue[0]();
_thisWait = _thisQueue[1];
} else {
_thisWait = _thisQueue;
}
// 関数とペアで登録されたwaitタイム後、次のキューへ
setTimeout(arguments.callee, _thisWait);
}());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment