Delaying Ajax-based validation triggers

When you're doing Ajax-based validation on a text input control, you really don't want your data calls firing off at every keyup event as this will put unnecessary load on your server. Instead, the thing to do is to wait a little while after the user's last key release to see if she's stopped typing before firing off a request.

I'm sure that there are hundreds of code snippets lying about for doing just this, and that JQuery probably already has something built in or a plugin for it, but a quick Google search didn't turn up anything for me so here I am, sharing my simple solution for delayed Ajax validation in JavaScript.

// A simple mechanism to handle delayed validation based on keyboard entry.
// Copyright (c) 2008, Aral Balkan, All Rights Reserved.
// Released under the MIT license.
validationFunctionRefs = [];
timers = [];
function callAfterDelay(fnRef, duration){

  // Check if a timer for this validation function is already in effect
  // and reset it if it is.
  for (i = 0; i < validationFunctionRefs.length; i++) {
    fnToCheck = validationFunctionRefs[i];
    if (fnToCheck == fnRef){
      timer = timers[i];
      clearInterval(timer);
      timers.splice(i,1);
                        validationFunctionRefs.splice(i,1);
                        break;
    }
  }

  timer = setTimeout(fnRef, duration);
  timers.push(timer);
  validationFunctionRefs.push(fnRef);

  return timer
}

To use it, simply call callAfterDelay from your event handler for the keyup event. e.g., in JQuery:

$("#id_vat_no").keyup(function(){callAfterDelay(checkVatNumber, 500)})

In this case, 500ms after the user stops typing in a text input, the checkVatNumber method will make a JSONP call to the European VAT Number Validation service to see if the entered VAT number is valid.

Comments