0

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);
        }
    }
};
urSus
  • 12,492
  • 12
  • 69
  • 89

1 Answers1

-1

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;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • but my cancel() function doesnt get executed until they are all done, how would I then change that global variable? – urSus Sep 04 '17 at 15:52
  • @urSus mayve dont fill the event queue? Your code would be helpful to solve this... – Jonas Wilms Sep 04 '17 at 15:53
  • okay ive edited the question @Jonas w. How would I not fill it up? Isnt that what JS uses inherently? – urSus Sep 04 '17 at 15:57
  • I dont see how, I cant use setInterval. I only want to cancel the operation if user does so. In your case the cancel mutation method will get executed while the callback running? – urSus Sep 04 '17 at 16:02