PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Wait for stuff in javascript

This could be useful when on the browser we needed to wait for some stuff to happen or finish before I start processing a block of code. Here are some useful functions that can be quite handy

Waiting for all ajax requests to finish (uses jquery).

This uses the query $.active property to see the count of ajax requests currently active. when its 0 it indicates no ajax activity happening currently. The function below checks asynchronously for it every half a second until all the current request finishes.

 function waitForPendingAjax(callBack)
 {
    window.setTimeout(function(){
    if($.active == 0){
      callBack();
    }else{
      waitForPendingAjax(callBack);
    }
    },500);
 }

the following is a sample to use the above function

  waitForPendingAjax(function(){
      console.log("no ajax requests happening now");
  });

Waiting for an element to load (uses jquery)
This function asynchronously checks every half a second if an element is loaded.

 function waitForElement(elementPath, callBack){
   window.setTimeout(function(){
    if($(elementPath).length){
      callBack(elementPath, $(elementPath));
    }else{
      waitForElement(elementPath, callBack);
    }
   },500);
 }

the following is how to use it

 waitForElement("#my-div", function(){
   console.log("my-div is now loaded");
 });

This logic can be extended to lots of other things on the browser like checking waiting for an element to be visible, element to get enabled, some variable to attain a certain value etc.

Updated: March 23, 2018 — 11:14 am

1 Comment

Add a Comment

Leave a Reply

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

PM's Blog © 2018