I am doing "heavy" canvas operations in a jQuery each loop causing slower devices (IE and the iPad) to sometimes become totally unresponsive.
So I was thinking I could use underscore's _.defer()
to queue the functions in my each loop like:
function handleAsset = _.defer(function(){
//weightlifting goes here (partly async)
});
$.each(assets, handleAsset);
Yet this throws a weird error (the stack trace points to the $.each
):
Uncaught TypeError: Object 20877 has no method 'call'
Is this approach flawed? Is this due to async operations going on inside the handler function? Is there another / a better way to achieve this?
So you want to limit the number of concurrent asynchronous operations? The flaw in your implementation is that you will be deferring each action until the previous one has completed.
One option is to use a sequence helper, you could then break this queue up into more manageable chunks for processing.
https://github.com/michiel/asynchelper-js/blob/master/lib/sequencer.js
If you split your actions array into two arrays, and have them run side by side you would then only ever have two processes running at a time until both queues have completed.
e.g.
It is flawed. You should try to decouple / break up code at the lowest point possible. I think its unlikely that just decoupling each iteration of a loop is enough on the long run.
However, what you really need to do is, to setup an asyncronous runaway timer which gives the implementation enough room to update the UI Queue (or UI thread). This typically is done using methods like
setTimeout()
(client),nextTick
(node.js) orsetImmediate
(coming soon).For instance, lets say we have an array, and we want to process each entry
Now this code is a classic loop, iterating over the array and process its data. It'll also consume 100% CPU time and will therefore block the browsers UI queue as long as it takes to process all entries (which basically means, the browser UI will freeze and become unresponsive).
To avoid that, we could create a construct like this:
What happens here ?
What we're basically doing is:
setTimeout
) and give the UI a chance to updateAny delay above 100 ms is typically recognized by the human eyes as "lag". Anything below that seems fluently and nice (at least our eyes will tell us so). 100ms is a good value as limit for maximum processing times. I'd even suggest to go down to 50ms.
The caveat here is that the overall processing time will increase, but I think its a better deal to have longer processing and stay responsive, instead faster processing and a very bad user experience.
Quick Demo: