Jquery delay event until the user has finished typing

A function to be launched let's say a second and a half after the user has finished typing the last type. I have this piece of code but everytime that the user is making one type the script is launched which I don't want:

$(document).ready(function()
{
  var $firstname    = $("#firstname");

  $firstname.keyup(function()
  {
    var content = $("#firstname").val();
    $.post("ajax.php", { firstname: content}, function(result){
        var contentDiv = $("#ContainerValidation");
        contentDiv.fadeOut(400, function(){ contentDiv.html(result); });
        contentDiv.fadeIn(400);
        contentDiv.fadeOut(5000);
      });
    });
});

Thanks for your help.

Upvotes: 3

Views: 4747

Answers (2)

Felix Kling
Felix Kling

Reputation: 817228

I think it would be sufficient to start a timer that waits 1.5 seconds and is aborted if the user continues typing during that time:

function send() {
    $.post("ajax.php", { firstname: $firstname.val()}, function(result){
        $("#ContainerValidation")
           .fadeOut(400, function(){ $(this).html(result); })
           .fadeIn(400)
           .fadeOut(5000);
    });
}

var timer = null;
$firstname.keyup(function() {
    clearTimeout(timer);
    timer = setTimeout(send, 1500);
});

Upvotes: 6

ThiefMaster
ThiefMaster

Reputation: 318808

What you'll want is a debouncing script.

A very easy solution would be embedding the Underscore.js library, it contains such a function: http://documentcloud.github.com/underscore/#debounce

You'd use it like this:

$firstname.keyup(_.debounce(function () {
    var content = $("#firstname").val();
    $.post("ajax.php", {
        firstname: content
    }, function (result) {
        var contentDiv = $("#ContainerValidation");
        contentDiv.fadeOut(400, function () {
            contentDiv.html(result);
        });
        contentDiv.fadeIn(400);
        contentDiv.fadeOut(5000);
    });
}, 1500));

Upvotes: 3

Related Questions