Using JavaScript’s setTimeout() Method

By Michael Bradley, CorasWorks Professional Services Consultant

On a recent engagement I was running into performance issues in the customer’s environment when trying to use JavaScript to update a report client-side for a custom hierarchal KPI report that rolls up worst-case KPIs.  The customer only has Internet Explorer 8 in their environment and I quickly discovered that IE8’s JavaScript engine is notoriously slow as compared to the newer IE9 and IE10.   The problem was that the users would receive a “Stop script” alert every time they would try to apply a filter to the report, which would require a recalculation of the KPI indicators.

While not a complete game stopper since you can simply select “No” and let the script continue running, most users would select “Yes” to stop the script and return to the report.  Of course the report would be incomplete since the recalculation function had not finished its job of updating the report.  Add to this the delays and apparent slow performance of the report and a new strategy needed to be applied to the recalculation function of the report.

At the suggestion of a more seasoned solution architect on my team, I looked at leveraging JavaScript’s setTimeout() method to improve the report’s performance and the overall user experience.   The beauty of adding setTimeout() to my existing report and code was that it only required minor changes.   The first step was to wrap discreet sections of the report in a <tbody> tag.  This allowed me to pass smaller sections of the report to the recalc function instead of passing the entire report.  The next step was to make use of setTimeout() when calling the recalc function.  The syntax in my report’s script looks like this:

var t = setTimeout (recalcFunction(tbodyID),0);

or, more generically:

var id = setTimeout (fn, delay);

What’s going on here is that I am assigning the setTimeout() function to a variable ‘t’, that will store the unique ID for the timer.  Within the setTimeout() function I tell it to run my recalcFunction() with the id of the tbody tag that I want the recalc to update as a parameter and that I want to wait “0” milliseconds before doing so.  Adding this one line of code to the logic of the report after a user applies a filter to narrow the report’s results, greatly improved the performance of the report within IE8 resulting in a “win” for this solution.

Here’s another blog article that provides a more detailed explanation of how JavaScript timers work.


Comments are closed.