How to prepend message to Javascript event queue? (Canceling long running methods)

44 views Asked by At

I have a nonstandard scenario, I am making a embedded ebook reader which uses webview to show local html epub files.

What I do is via ajax I load all the html files, parse their contents and append them to body, ajaxes area quick but the callbacks that do the appending take some time. Their run in parallel but callbacks run synchronously, on the same JS thread and are queued up via message loop.

No I need to cancel this operation, however as the cancel call is just another message that gets queued up, this obviously runs after all callbacks are done, which obviously has no use for me. Any way to clear these callbacks from javascripts event queue or prepend new message?

Thanks

var requestsInFlight;

loadAllSpineElements = function(spineElementsCount) {
    requestsInFlight = new Set();
    for (i = 0; i < spineElementsCount; i++) {
        loadAndAppendSpineElement(innerWrapperDiv, pageCounts, requestsInFlight, i);
    }
};

loadAndAppendSpineElement = function(innerWrapperDiv, pageCounts, requestsInFlight, spineElementIndex) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

            // Long running dom operation

            requestsInFlight.delete(this);
            if (requestsInFlight.size <= 0) {
                handleAllSpinesLoaded(pageCounts);
            }
        }
    };
    xhttp.open("GET", "file:///localurl");
    xhttp.send();

    requestsInFlight.add(xhttp);
};

cancelAll = function() {
    if (requestsInFlight) {
        for (var it = requestsInFlight.values(), ajax = null; ajax = it.next().value;) {
            ajax.abort();
            requestsInFlight.delete(ajax);
        }
    }
};
1

There are 1 answers

4
Jonas Wilms On

No, but you can cancel them if they get executed. E.g:

var cancel = false;

setInterval(function(){
  if(cancel) return;
  alert("wohoo");
},1000);

So if you wanna cancel the events:

cancel = true;