JavaScript, jQuery and 'this': what happens here?

This is more a question of what happens in my code. It works, but I need to enlighten a little ...

I am using jQuery to create an event listener on a text input element. HTML will look like this:

<input type="text" id="autocomplete" size="50" />

I need to receive events whenever someone enters something into this field, and in order not to flood events, I set up an event listener with a timer so that my event listener code is executed only if the user did not type anything for 125 ms:

jQuery('#autocomplete').keyup(function(e) {
  e.preventDefault();
  clearTimeout(this.timer);
  this.timer = setTimeout(function() {
    jQuery.getJSON([URL goes here], function(data) {
      // processing of returned data goes here.
    }
  }, 125);

console.log(this);
});

, , , . , ID , . , this.timer. this . , console.log:

<input type="text" id="autocomplete" size="50" />

ID ? , - . " ", - ?

+5
1

, - DOM. DOM , , , , DOM . , , timer. , , . IE , DOM node, node . , console.log DOM node, , .

, DOM , . , , , .

(function($) {

    // Static variable for this function
    var keyupTimer;

    // Event handler for keyup
    $('#autocomplete').keyup(function(event) 
    {
        event.preventDefault();

        clearTimeout(keyupTimer);

        keyupTimer = setTimeout(function()
        {
            $.getJSON([URL goes here], function(data)
            {
                // processing of returned data goes here.
            }
        }, 125);
    });
})(jQuery);
+2

All Articles