Q:

How to wait for a button to complete its task then execute the next line of code

I have a button as follows that I programmatically click. 
document.getElementById("generateButton").click();

This button creates a table and loads the data from the database. 
I then have options to sort the table that if specified in the url, the table will be sorted once loaded.
if(COL_ONE == "true")
            sortTable("COL_ONE");

My problem is that the table takes around 3 seconds to load. Therefore, the if statement where the sorting happens, ends up running before the table is created. Therefore, the sorting does not occur. If I place a break point at the if statement and stop execution at the if statement, and wait until I see the table load, then run the if statement (through the debugger) then my sorting does work. Therefore, the code is all working, its just a matter of figuring out a way to stall until the table is loaded. Is there anyway I can do this, where until the table is loaded, then run the next if statement, I am doing this on page load. 

A:

You can make use of callback in this case
function tableLoaded(callback) {
   //Code to load the table
   callback();
}

In your main function
tableLoaded(function(){
   //have your if statement
   if(COL_ONE == "true")
      sortTable("COL_ONE");
});

