Polling Data with JavaScript’s setInterval() Function

I wrote earlier this year about making use of JavaScript’s setTimeout() function to improve the efficiency of some custom JavaScript/jQuery I wrote for a complex hierarchical report. Using setTimeout, the report let users quickly see the health of numerous projects that needed to update many columns and rows of results based on the user’s filter and view selections.

The setTimeout() function also has a very useful cousin called setInterval() that lets us call a function repeatedly until we either tell it not to with clearInterval() or the user closes the window. We can use this function to automatically update a section of a page with current information from a SharePoint list/library or other data sources. A good example of why we would do this is retrieving the number of the tasks for the currently logged in user that are past due. By wrapping an AJAX request to our CAPS service in a setInterval() function on a frequent interval (say every 60 seconds – 60000 miliseconds), we can unobtrusively and asynchronously update a past-due task notification on our custom page.

After our page loads we simply make a call to some custom script with setInterval() like this:

setInterval(getPastDueTasks(currentUser), 60000);

What we are doing here is calling our function  - getPastDueTasks(currentUser) – that makes our CAPS call to our task list using AJAX. Because we set the interval to 60000 milliseconds, our task list will be polled every minute. On success, our AJAX request will update an object on our page with the number of tasks that are past due and show a large red exclamation point if there are any. Since we’ve also made the object a hyperlink, the user can bring up the list of past due tasks so they can take action on them.

This is just on example, but I know you all are a creative lot so have fun with this and keep building.

Comments are closed.