nitsua
nitsua

Reputation: 793

Is it possible to stop currently executing Javascript code?

I'm not sure if what I'm about to ask is possible or the right way of doing about things, but here goes.

I have a webpage which loads some data from a server using AJAX and displays it visually. The user has the option of using one of two buttons on the page to "scroll" through the data which is filtered by week. The code for these buttons is something like:

$("#leftButton").click(function () {
    clearCurrentlyDisplayedData();
    changeFilter(1);   //Or -1, or whatever.
    loadAndDisplayData();
}

In this (simplified) example, loadAndDisplayData() would use AJAX calls to fetch this data and then display it on completion of the request, like:

$.get(
    "web/service/address", 
    function (data, textStatus, jqXHR) {
     //Display the data here
});

However, there is a problem when the user clicks the arrows to scroll through the data too quickly. If the buttons are clicked twice in quick succession, the data for two weeks is displayed, on top of each other.

I don't want to disable the buttons until the data is collected - since the data collection and displaying does take a little bit of time, this would kill the ability of the user to navigate through the site quickly, and would quickly become irritating.

Is it possible to kill any currently executing scripts or AJAX calls (or functions called as a result of these) when the user clicks on one of the buttons in order to prevent the loading of two sets of data? Is there any other way I can go about solving this problem?

Upvotes: 2

Views: 179

Answers (2)

wrschneider
wrschneider

Reputation: 18780

Is there any other way I can go about solving this problem?

Rather than aborting the requests, it might be better to construct the callback function inside $.get in a way that clears the data and displays the new data as a single operation - i.e., doesn't clear the data until the new data is ready.

Javascript only processes a single event/thread at a time, so each AJAX response will be processed serially as they arrive.

Upvotes: 1

Matt
Matt

Reputation: 75317

The jqXHR object has an abort() method, which you can call to cancel an AJAX request.

However, this requires you to keep a reference to the object returned by $.get().

A prehaps easier approach would be to increment a global counter when making a request, and decrement it when a request completes. In your success handler, only show the results if the counter === 0 (e.g. theres no requests pending).

Upvotes: 3

Related Questions