Created
March 6, 2014 10:13
-
-
Save jonyardley/fe0ed63ad6dece42c1f4 to your computer and use it in GitHub Desktop.
JS Non-bocking Loop / Queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(['app'], function(App){ | |
//script inspired by: http://debuggable.com/posts/run-intense-js-without-freezing-the-browser:480f4dd6-f864-4f72-ae16-41cccbdd56cb | |
App.queue = function(){ | |
var queue = { | |
_timer: null, | |
_queue: [], | |
add: function(queueName, fn, context, time) { | |
var setTimer = function(time) { | |
queue._timer = setTimeout(function() { | |
time = queue.add(); | |
if (queue._queue.length) { | |
setTimer(time); | |
}else{ | |
queue.done(queueName); | |
} | |
}, time || 0); | |
}; | |
if (fn) { | |
queue._queue.push([fn, context, time]); | |
if (queue._queue.length === 1) { | |
setTimer(time); | |
} | |
return; | |
} | |
var next = queue._queue.shift(); | |
if (!next) { | |
return 0; | |
} | |
next[0].call(next[1] || window); | |
return next[2]; | |
}, | |
clear: function() { | |
clearTimeout(queue._timer); | |
queue._queue = []; | |
}, | |
done: function(queueName){ | |
App.vent.trigger(queueName + ':queue:done'); | |
} | |
} | |
return queue; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment