Edited at

メモ:rafでdelay処理

More than 3 years have passed since last update.


function delay(cb, delayTime, everyTimeCb){
var cancel = false;
delayTime = delayTime || 0;
(function(){
var baseTime;
var raf = window.requestAnimationFrame;
raf(function(now){
baseTime = baseTime || now;
var elapsedTime = now - baseTime;
if(elapsedTime >= delayTime){
cb(now);
}
else{
everyTimeCb( elapsedTime );
cancel || raf(arguments.callee);
}
});
})();
return function(){
cancel = true;
};
};

使い方

// 5秒後に実行

var cancel = delay(function(){ ... }, 5000);

// 中止
cancel();

// 経過時間をみる
delay(function(){ ... }, 5000, function(elapsedTime){
console.log(elapsedTime + 'ms経過');
});