'Stop js function if another onclick event happends
So I have this function which loads the content of different .php pages depending on which button i click. But if I click on one of the buttons and the .php content isn't fully loaded and i then click on another one, then the old content still loads in when its done.
So I want to stop the function from finishing if the user decides to click on another button
<div class="wdc-background">
<!-- Menu -->
<div class="wdc-table-menu">
<ul id="menu_wdc">
<li><a class="wdc-btn active" href="#" onclick="loadTab('wdc_tab')">WDC</a></li>
<li><a class="wdc-btn" href="#" onclick="loadTab('history_tab')">History</a></li>
<li><a class="wdc-btn" href="#" onclick="loadTab('components_tab')">Components</a></li>
</ul>
</div>
<div id="wdc_tab_fields" class="wdc_tab_fields"></div>
</div>
<script type="text/javascript">
window.onload=loadTab('wdc_tab');
</script>
The js function, which somehow should detect if it should stop loading if another button has been clicked, so it doesn't load the content of it all.
function loadTab(tab) {
console.log(tab);
menu_functionallity();
wdc_tab_fields = document.getElementById("wdc_tab_fields");
wdc_tab_fields.innerHTML = "<img class='svg-color' style='margin-left: auto; margin-right: auto; display: block; padding: 2rem;' src='../images/svg/grid.svg'/>";
var request_object = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
if (tab == "") {
wdc_tab_fields.innerHTML = "ERROR - Query is empty";
return false;
}
request_object.open("GET", "../pages/wdc-pages/" + tab + ".php", true);
request_object.send();
request_object.onreadystatechange = () => {
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
if (request_object.readyState !== request_object.DONE) {
wdc_tab_fields.innerHTML = "ERROR - " + request_object.readyState + ": " + dict[request_object.readyState];
return false;
}
if (request_object.status != 200) { // Normal http request return status
wdc_tab_fields.innerHTML = "ERROR - Loading " + tab + " content";
return false;
}
wdc_tab_fields.innerHTML = request_object.responseText;
if (tab == "wdc_tab") {
loadCanvas("wdc_canvas");
}
return true;
}
}
Solution 1:[1]
Either you do a check to see if the tab has been changed
var activeTab;
function loadTab(tab) {
activeTab = tab;
....
request_object.onreadystatechange = () => {
if (activeTab != tab) return;
...
or you can abort the call if active
var request_object;
function loadTab(tab) {
if (request_object && !request_object.DONE) request_object.abort();
request_object = new XMLHttpRequest()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | epascarello |
