2017-09-04 56 views
0

我有一個非標準的場景,我正在製作一個嵌入式電子書閱讀器,它使用webview顯示本地html epub文件。如何在Javascript事件隊列中添加消息? (取消長時間運行的方法)

我所做的是通過ajax我加載所有的html文件,解析它們的內容並將它們追加到body,ajaxes區域,但追加的回調需要一些時間。它們並行運行,但回調在同一個JS線程中同步運行,並通過消息循環排隊。

不,我需要取消這個操作,然而,因爲取消調用只是另一個排隊等待的消息,這顯然會在所有回調完成後運行,這顯然對我沒有用處。任何方式來清除javascripts事件隊列的這些回調或prepend新消息?

感謝

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

沒有,但你可以取消他們是否得到執行。 E.g:

var cancel = false; 

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

所以,如果你想取消的事件:

cancel = true; 
+0

但我取消()函數犯規得到執行,直到他們完成所有的工作,我將如何再改變全局變量? – urSus

+0

@urSus可能不會填充事件隊列?你的代碼將有助於解決這個問題... –

+0

好吧我編輯了這個問題@Jonas w。我怎麼不填補它?是不是JS使用固有的? – urSus