Closing JavaScript onKeyUp with timeout

I am trying to assign an onKeyUp event to all inputs on the form using closure. the array fieldscontains all the field names that require the event assigned to them. The array ajaxFieldscontains the names of the fields (from the array fields) that require ajax validation.

function createEvents(fields,ajaxFields) {
    for(var x=0;x<fields.length;x++) {

        $('input[name='+fields[x]+']').keyup(function(field) { 
        //assign an onKeyUp event
            return function() {
                //some code using variable 'field' and array 'ajaxFields'
        }(fields[x]));
    }
}

I would like the onKeyUp function to be executed a second after the user has finished typing in this field, insted every time the key is up (onKeyUp). this will save a lot of processing space, not to mention ajax calls. While I use this:

clearTimeout(timer);
timer = setTimeout('validate()' ,1000);

You may have noticed that the function validate()does not exist, and that is because I do not know how to wrap the closure inside the named function, and I'm not even sure if I should ...

So how do I do this?

EDIT: fiddle

+3
2

( ) setTimeout .

clearTimeout(timer);
timer = setTimeout(function(){
    // your code here
}, 1000);

, keyup, - :

$('input[name='+fields[x]+']').keyup(function(field) { 
//assign an onKeyUp event
    return function() {
        var that = this,
            $this = $(this);
        clearTimeout($this.data('timeout'));
        $this.data('timeout', setTimeout(function(){
            //some code using variable 'field' and array 'ajaxFields'
            // "this" will not be your element in here, make sure to use "that" (or "$this")
        }, 1000));
    };
}(fields[x]));

- $this.data, - .

: http://jsfiddle.net/Z43Bq/3/

+2

:

var timer;

$(document).ready(function() {
    var fields = $('.field');
    var ajaxFields = $('.ajax-field');

    createEvents(fields, ajaxFields);
});

function createEvents(fields,ajaxFields) {
    // Use jQuery "foreach" method
    $(fields).each(function(inx, field) {
        // Bind the listener here
        $(field).keyup(function(ev) {
            // Clear timeout if necessary
            if (timer != null) clearTimeout(timer);

            // Set the timeout
            timer = setTimeout(function() {
                // Your code should here

                console.log('Fields: ', fields, '\nAjax Fields: ', ajaxFields, '\nTHE field: ', field);
            }, 1000);
        });
    });
}

: http://jsfiddle.net/BLyhE/

+1

All Articles