Skip to content

Instantly share code, notes, and snippets.

@dtipson
Last active December 15, 2015 18:03
Show Gist options
  • Select an option

  • Save dtipson/4fbf36adedeb80a8bd84 to your computer and use it in GitHub Desktop.

Select an option

Save dtipson/4fbf36adedeb80a8bd84 to your computer and use it in GitHub Desktop.
requestIdleCallback usage pattern that simplifies things a tiny bit
//always include a polyfill that falls back to setTimeout(cb,1) https://gist.github.com/paullewis/55efe5d6f05434a96c36
//or possibly something better https://github.com/PixelsCommander/requestIdleCallback-polyfill
//calling this function creates and returns a new stack of idle functions,
//and exposes an addTasks method that will add more to the stack as needed and return a cancelIdleCallback cancelable id
function createIdleStack(){
var bgtasks = [];//array of all tasks
function backgroundTask(deadline){
//does each task in order, checking to see if there's time left
while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && bgtasks.length > 0) {
bgtasks.shift()();
}
if (bgtasks.length > 0) {
requestIdleCallback(backgroundTask,{timeout:bgtasks.timeout});
}
}
//method of adding tasks to the stack, with optional last "timeout" parameter
bgtasks.addTasks = function(/*...tasks, optional ops*/){
var args = Array.prototype.slice.call(arguments),//or Array.from
cachedLength = bgtasks.length;
bgtasks.timeout = (args.length && args[args.length-1].timeout)? args.pop().timeout : {};
if(args.length){
bgtasks.push.apply(bgtasks,args);
if(!cachedLength || !bgtasks.id){//if the stack is clear or there's no callbackid, create a new stack
return bgtasks.id = requestIdleCallback(backgroundTask,{timeout:bgtasks.timeout});
}else{
return bgtasks.id;//otherwise just return the existing id, there's already a callback in the wild
}
}else{
throw Error('no tasks');
}
};
//returns an id that can be used to cancel this entire stack, if needed
return bgtasks;
}
//USAGE
//var idleStack = createIdleStack();
//var cancel = idleStack.addTasks(function(){console.log('test')},function(){console.log('test2')});
//var cancel = idleStack.addTasks(function(){console.log('test3')},function(){console.log('test4')});
////cancelIdleCallback(cancel);//if run immediately or soon enough after adding tasks, will cancel everything remaining
//otherwise, functions passed as arguments passed to addTasks will get queued up to run when there's time.
//If you plan to cancel a stack, make sure to update the id with each new call to addTasks
//you can't really _know_ whether or not the first call will have completed, so it may have made a new call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment