0

I have some ajax code that updates a doc in the db

  // Updates to INPUTS, on.input..
jQuery(function ($) {
    $(document).on('input', '.updateThisClass', function () {
        var $this = $(this);
        var number = $this.data('id');
        console.log("index # of doc updated: " + number);
          //THIS IS LOGGED WITH EVERY CHARACTER ENTERED

        // make an ajax call
        $.ajax({
            dataType: 'json',
            data: $('#theForm' + number).serialize(),
            type: 'POST',
            url: "http://localhost:9999/update",
            success: gotAllSuccess,
            error: gotAllFailure
        });

    });
})

.input is too fast though, and updates on every single character!

How can a Timer be added to the .input part of this function? Or is there an event for multi-char-inputs?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
StackThis
  • 883
  • 3
  • 15
  • 45
  • 7
    You want to "debounce" the event. See this plugin: http://benalman.com/projects/jquery-throttle-debounce-plugin/ – gen_Eric Feb 26 '14 at 21:08
  • 2
    In addition [Underscore.js](http://underscorejs.org/) has a number of helpful function functions like [debounce](http://underscorejs.org/#debounce) and [throttle](http://underscorejs.org/#throttle). – asawyer Feb 26 '14 at 21:09
  • @RocketHazmat awesome! am reading up on this right now – StackThis Feb 26 '14 at 21:16

1 Answers1

2

You want to "debounce" the event function. This will wait until the user has finished inputting text before running the function.

It's normally done using setTimeout/clearTimeout. You clear and re-set a timeout each time the event runs. Then when the event stops triggering, the function runs (after the timeout period).

Here's an example:

$('#input').on('input', function(e){
    var $this = $(this);

    clearTimeout($this.data('timeout'));

    $this.data('timeout', setTimeout(function(){
        console.log($this.val());
    }, 250));
});

If you like, there is also a jQuery plugin that can take care of the timeouts for you. Here's a link: http://benalman.com/projects/jquery-throttle-debounce-plugin/

Using the plugin, the code would look like:

$('#inputC').on('input', $.debounce(250, function(e){
    console.log($(this).val());
}));

Here's a live demo: http://jsfiddle.net/KP5rM/1/

gen_Eric
  • 223,194
  • 41
  • 299
  • 337