I have a cpu intensive task that I need to run on the client. Ideally, I\'d like to be able to invoke the function and trigger progress events using jquery so I can update
My strongest recommendation is to display a simple loading.gif during the operation. User often accepts some duration if they have been "told" that it could take some time.
Ajaxload - Ajax loading gif generator
Great answer Kevin! I wrote something similar a few years back, though less sophisticated. Source code is here if anyone wants it:
http://www.leapbeyond.com/ric/jsUtils/TaskQueue.js
Anything with a run()
method can be queued as a task. Tasks can re-queue themselves to perform work in chunks. You can prioritize tasks, add/remove them at will, pause / resume the entire queue, etc. Works well with asynchronous operations - my original use for this was to manage several concurrent XMLHttpRequests.
Basic usage is pretty simple:
var taskQueue = new TaskQueue();
taskQueue.schedule("alert('hello there')");
The header comments in the .js file provide more advanced examples.
This is a very basic example of how to create threads in JavaScript. Note that is is up to you to interrupt your thread functions (yeld instruction). If you want, you can use a setTimeout instead of my while loop to run the scheduler periodically. Note also that this example only works with JavaScript version 1.7+ (firefox 3+) you can try it here: http://jslibs.googlecode.com/svn/trunk/jseval.html
//// thread definition
function Thread( name ) {
for ( var i = 0; i < 5; i++ ) {
Print(i+' ('+name+')');
yield;
}
}
//// thread management
var threads = [];
// thread creation
threads.push( new Thread('foo') );
threads.push( new Thread('bar') );
// scheduler
while (threads.length) {
var thread = threads.shift();
try {
thread.next();
threads.push(thread);
} catch(ex if ex instanceof StopIteration) { }
}
The output is:
0 (foo) 0 (bar) 1 (foo) 1 (bar) 2 (foo) 2 (bar) 3 (foo) 3 (bar) 4 (foo) 4 (bar)