I'm working on a javascript client-side project that performs some heavy computing and at the same time needs to be user friendly. This means asynchronous functions of course, but also letting the user do something while the heavy tasks are performed by the computer.
Take this as an example of asynchronuos loop:
function async_operation(){
function do_stuff(){
var i=0;
while(i<1000000000){
... //do some stuff (to be more specific: localforage.setItem)
++i;
}
}
setTimeout(do_stuff, 0);
//do next opearions...
}
This loop works perfecly and asynchronuosly, the problem is that if the user clicks on something, for example this button:
<button onclick="alert('hello')">click me</button>
the alert message pops up just after the loop has finished! So the user cannot click on anything before the function has finishes.
Is there any way to let the user trigger some events during this task?
Replace the while loop with a recursive function.
Call each iteration of the function using setTimeout
.
function do_stuff() {
var i = 0;
really_do_stuff();
function really_do_stuff() {
//do some stuff (to be more specific: localforage.setItem)
++i;
if (i < 1000000000) {
setTimeout(really_do_stuff, 1);
} else {
//do next opearions...
}
}
}
You might want a while loop inside really_do_stuff
so that you can have batch sizes greater than 1
since setTimeout
will introduce a lag (and thus a performance penalty).