Cancel a scheduled task in javascript

More than often, the application UI consists in one master table that is used to refresh a slave one (item-details view).

When the user selects one record of the item list, the detail frame is refreshed with the fields related to this item. We use AJAX request to refresh the detail view.

However, multiple useless requests may occur when the user scrolls quickly through the master table. This can be avoided if we decide to refresh the detail view only if the user selection remains the same for a certain time.

The example below presents such mechanism.

The showDetails() function is called by a UI event such as onMouseOut().  The trick consist in delaying the refresh (by one second here), via a setTimeout() function. We keep track of the scheduled call in a global variable. This allow us to cancel the request in case another item in selected in the meantime.

var reqID = null; // Global var to avoid multiple requests when scrolling through the Item table
function showDetails(selectedItem) {
    if (reqID){
         // If an delayed AJAX call was already scheduled , we cancel it
 // Schedule a delayed ajax call (1s)
 reqID = setTimeout( function() { myMagicAjaxCall(selectedItem);}, 1000);

Thanks to StackOverflow article for the initial suggestion

One thought on “Cancel a scheduled task in javascript”

  1. Hi mister de Méringo, comment vas tu depuis toutes ces années ? Je vois qu’on donne tous les deux dans des webs différents, mais pourtant si proches…

    En tout cas, je suis content de te savoir toujours en vie 🙂

    A bientôt, peut être!

    Nicolas Simonnet

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.