Skip to content Skip to sidebar Skip to footer

Is There A Way To Make Multiple Html5 Filereader.onload Events Fire Sequentially?

I am using the html5 filereader API to get photos locally without the user having to upload them. In browsers that support it I am allowing multiple selections so I am looping thro

Solution 1:

The onload events do fire sequentially, the handler is not executed while an other one is currently processed ("JS is single-threaded"). This of course does not count when you start some asynchronous processing (timeouts, animations, file loads) in a handler.

In that case, you will need to manually handle the sequential processing. It's easy using a queue of waiting processes which are executed when one is finished:

var waiting = [];
// …create many parallel loaders, and on each:
    ….onevent = execute;

function execute(e) {
    if (waiting.active)
        waiting.push(e);
    else {
        waiting.active = true
        // do something that takes its time, supplying a
          … function callback(ready) {
            waiting.active = false;
            if (waiting.length)
                execute(waiting.shift()); // go on with next
          }
    }
}

However, it seems to me that not renderSlide is causing the problems, but that you instantiate so many FileReaders at the same time. Make them start loading files one after the other, by turning your for-loop into an asynchronously called "recursive" function:

var files = […]
(function handle(i) {
     if (i >= files.length) return;
     // create loader
     ….onevent = function(e) {
          // do processing, and then call
          handle(i+1);
          // or call that from another callback if you want to do async
          // processing, like "renderSlide"
     };
})(0);

Solution 2:

The events do fire sequentially. Javascript is single-threaded, so while one of your event handlers is executing, no other event will fire, and also your browser* remain be unresponsive, as its single thread is occupied by running your Javascript event handler. It is not enough to execute your entire renderSlide() in a setTimeout, because the browser will still be locked for the duration of the entire renderSlide() execution. You will need to break the actual logic inside renderSlide() into separate chunks each of which you can postpone using setTimeout(chunk, 1), giving the browser a little breathing room to maintain responsiveness.

* Actually, it might not be the entire browser that is locked up — it could be just one tab or a group of related tabs running in a single thread. Actual browser architectures differ.


Post a Comment for "Is There A Way To Make Multiple Html5 Filereader.onload Events Fire Sequentially?"