CF, jQuery, Session timeout countdown

jQuery Logo




Certain ColdFusion applications are written in such a way that after the session times out, the user is also logged out.  This is sometimes to secure the application from others accessing the computer, while the real user is away from their desk.  If this is the case, it’s nice to let the user know how long they’ve got left before they’re logged out due to inactivity.


  • User logs in, session created.
  • Session set to time out (e.g. 30 minutes).
  • When session times out, the user is logged out.
  • Display a countdown so the user knows how long is left.
  • Inform the user when they are approaching the limit (e.g. 5 minutes left).
  • Let the user know that they’ve been automatically timed out due to inactivity..

Approach taken

  • Every request to the application will set two cookies:
    • Date / time the session will expire.
    • Current server date / time.
  • Our bit of JavaScript watches these cookies.
  • Any application activity will update these cookies so we know if a second window has done something and the session timeout refreshed.


This is my first real effort at creating a jQuery plugin.  It took a bit more effort wrapping everything up nicely and providing options but I think it was worth it and should make the code easier to include.

(function($) {
  $.fn.sessionTimeout = function (options) {
    var opts = $.extend({}, $.fn.sessionTimeout.defaults, options);
    var inter ='timer');
    if (inter) {

    var info = {
      warned: false,
      expired: false
    processCookie(info, opts);'timer', setInterval(cookieCheck, opts.interval, this, info, opts));
    cookieCheck(this, info, opts);

  function processCookie(info, opts) {
    info.serverTime = Date.parse($.fn.sessionTimeout.readCookie(opts.timeCookie));
    info.sessionTime = Date.parse($.fn.sessionTimeout.readCookie(opts.sessCookie));
    info.offset = new Date().getTime() - info.serverTime;
    info.expires = info.sessionTime + info.offset;
    info.duration = Math.floor((info.sessionTime - info.serverTime) / 1000);

  // private
  function cookieCheck(els, info, opts) {
    var sessionTime = Date.parse($.fn.sessionTimeout.readCookie(opts.sessCookie));
    if (sessionTime != info.sessionTime) {
      processCookie(info, opts);
    info.timeLeft = {};
    var ms = info.expires - (new Date().getTime());
    info.timeLeft.minutes = Math.floor(ms / 60000);
    info.timeLeft.seconds = Math.floor(ms % 60000 / 1000);
    info.timeLeft.onlySeconds = info.timeLeft.minutes * 60 + info.timeLeft.seconds;
    info.timeLeft.minutes = info.timeLeft.minutes.toString().replace(/^([0-9])$/, '0$1');
    info.timeLeft.seconds = info.timeLeft.seconds.toString().replace(/^([0-9])$/, '0$1');
    if (!info.warned && info.timeLeft.onlySeconds <= opts.warningTime) {
      info.warned = true;
      opts.onWarning(els, info, opts);
    } else if (!info.expired && info.timeLeft.onlySeconds < 0) {
      info.expired = true;
      opts.onExpire(els, info, opts);
    if (!info.expired) {
      opts.onTick(els, info, opts);

  function onTick(els, info, opts) {
    els.each(function() {
      opts.onTickEach(this, info, opts);

  function onTickEach(el, info, opts) {
    $(el).html(info.timeLeft.minutes + ':' + info.timeLeft.seconds);

  function onWarning(el, info, opts) {

  function onExpire(el, info, opts) {

  // public
  $.fn.sessionTimeout.readCookie = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i=0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0)
        return unescape(c.substring(nameEQ.length,c.length));
    return null;

  $.fn.sessionTimeout.defaults = {
    timeCookie: 'SERVERTIME',
    sessCookie: 'SESSIONTIMEOUT',
    interval: 1000,
    onTick: onTick,
    onTickEach: onTickEach,
    warningTime: 3600, // seconds
    onWarning: onWarning,
    onExpire: onExpire

The plugin provides .sessionTimeout(options) which is used on your selected elements to display the amount of time left until session expiration.  The options allow you to use different cookie names, change the execution interval and override several events.

It works by setting up a periodic function to watch the cookies.  Whenever the cookies are updated, we recalculate the time out and continue displaying the information.  If the warning time or expiration is reached, it fires off over-ridable events that by default use “alert” to display simple messages, but could easily use something like the jQuery UI dialog plugin.

If you’re wondering about the reasoning behind the server time cookie.  This was to workaround the differences between the client and server clocks.


In the following code I’ll set the two cookies required for the plugin and use it against two different elements.  One for displaying the time, another to show a progress bar (using jQuery UI, not required for the plugin).  I also override the onWarning & onExpire events for the progress bar since the user wouldn’t like to be double prompted 😉

  <cfsetting showdebugoutput="false"></cfsetting>
  <!--- This bit of ColdFusion should live in your application.cfc onRequestStart() -->
  <cfset currenttime="Now()"></cfset>
  <cfset sesstimeout="DateAdd('n'," 2,="" currenttime)=""></cfset>
  <cfcookie name="servertime" value="#DateFormat(currentTime, 'yyyy/mm/dd')# #TimeFormat(currentTime, 'HH:mm:ss')#"></cfcookie>
  <cfcookie name="sessiontimeout" value="#DateFormat(sessTimeout, 'yyyy/mm/dd')# #TimeFormat(sessTimeout, 'HH:mm:ss')#"></cfcookie>

<div style="text-align: center; width: 200px;">
  <div class="sessions"></div>
  <div class="bar"></div>

The result should be the time counting down with a progress bar below it.  If you try this out for yourself, be sure to open two windows (same  browser) and refresh one, the other window should acknowledge the session refresh.  The same goes for any AJAX requests, as long as they are hitting your ColdFusion application.

As always, it’d be great to hear if anyone is doing something similar or wants to take advantage of this.

19 thoughts on “CF, jQuery, Session timeout countdown

    1. misterdai Post author


      Thanks. Your alternative plugin looks pretty good, I can see how you’d have problems with multiple browser windows though. Thanks to the use of cookies, I don’t have to worry about what type of request comes in (Ajax, normal or other) or how many windows are open. As long as the request hits a dynamic page (coldfusion, php or something else) then the cookies can be updated and all other windows will pick up the change. 😉

      Btw, loving your jQuery UI Growl plugin. Would be great if you added in themeroller support 🙂

    1. misterdai Post author


      Nice approach. Mine was originally plain JS using jQuery but I thought I’d try out this plugin business when I went to post it. It’s a great idea to give the user an option to refresh. I do something similar in a couple of my applications where I have a countdown timer displayed and a small button next to it that simply fires off an Ajax request to a practically empty ColdFusion page.

  1. Jules Gravinese

    Here is something simpler, for a 1 hour session timer:
    setTimeout("alert('Your Session will Expired in 5 minutes. Please navigate to a new page to reset the timer (1 hour).');", 54*60*1000);
    setTimeout("alert('Your Session will Expired in 1 minute. Please navigate to a new page to reset the timer (1 hour).');", 58*60*1000);
    setTimeout("document.location.href='/login/softlogout.cfm';alert('Your Session has Expired.');", 59*60*1000);

    1. misterdai Post author


      Just approved your comment, I guess thinks JavaScript in a comment is spam 😉

      I like your simple alternative, which I think would certainly do the job if you don’t let your user have multiple tabs open or do a lot of Ajax. I also think you’ve got a great idea where you redirect them to a page that logs them out. I’ve noticed that ColdFusion doesn’t garbage collect expired sessions instantly, so you might tell the user their session has expired but it might still be alive. Better off redirecting them and forcing the logout like your code does. 🙂

  2. Dr. Theopolis

    Can you enlighten me on how to call this so it displays the time countdown? Everything works for me otherwise. I get the timeout warning and the session end prompt fine. You’re example doesn’t include the call to the function in it. Thanks.

    1. misterdai Post author

      Sorry, guess I rushed this post and didn’t realise I missed out that bit. 🙂
      For the counter, you just need to have a HTML element on the page (or multiple if you want more than one). Then select it using jQuery by it’s ID / class or however you’re identifying it.


    1. misterdai Post author

      Hi Flavio, I’ve replied to the comment above. Let me know if it works as I don’t have a copy of that code locally or the spare time to test it at the moment. But off the top of my head, that should work 😉

  3. brilang

    Do you know of any way to display the timeout set by an application? Let’s say you’re working on a sub-system in a CF Application, and have not been given access to see the Application.cfc file, nor the session settings. I can dump the Session variable, but that doesn’t show me the sessiontimeout.

  4. rob_parkhill

    This fails on IE8. Any thoughts? It cab’t find the info/opts structures on the second call to the onTickEach function. Not really sure why? works fine in FF/Chrome but not IE, regardless of version.


    1. misterdai Post author

      Hi Rob, not sure one that one. I’ve been meaning to revisit this code for a while as I’m sure I could package it up as a jQuery plugin and make it a little more flexible. I’ll try and take a look at IE8 and let you know if I come up with anything 😉

    2. Sergey Babrenok

      I’ve faced IE8 issue too. I’ve changed the source code a little bit:

      var el= this;‘timer’,
      setInterval(function(){cookieCheck(el, info, opts);}, opts.interval));

      …and it works fine for me in IE8/FF/Chrome.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s