The "delete" wouldn't work, Andy - Sean's "upd" variable goes out of scope
immediately, and you need to use clearTimeout, not just delete the variable.

Sean, you can change your code to:

        var upd;
        $("input").keyup(function(){
                var self = this;
                clearTimeout( upd );
                upd = setTimeout( function() {
                        updateField( $(self) );
                },6000);
        });

You could also use an updated version of the $.expire plugin I posted a
couple of days ago:

(function( $ ) {
    $.expire = function( fn, callback, interval, start ) {
        var timer;
        function set() {
            timer = setTimeout( callback, interval );
        }
        if( start ) set();
        return function() {
            clearTimeout( timer );
            set();
            return fn && fn.apply( this, arguments );
        };
    };
})( jQuery );

Then your code would be:

        $("input").keyup( $.expire( null, function(){
                updateField( $(this) );
        }, 6000 ) );

That's more code overall, but it nicely encapsulates the timer logic in case
you need to do anything similar elsewhere in your code.

For this particular task, a simpler version of the plugin would also do the
trick:

(function( $ ) {
    $.expire1 = function( callback, interval ) {
        var timer;
        return function() {
            clearTimeout( timer );
            timer = setTimeout( callback, interval );
        };
    };
})( jQuery );

with your code being:

        $("input").keyup( $.expire1( function(){
                updateField( $(this) );
        }, 6000 ) );

As you can see, this version of the plugin is basically the same code as in
the standalone case.

-Mike

> From: Andy Matthews
> 
> Since you're setting the value of upd to a function 
> containing the setTimeout, you should be able to just
> 
> delete upd;

> From: Sean O
> 
> I'm trying to implement an autoSave function on my web application. 
> Something that automatically saves the contents of the 
> current field 6 seconds after the last keyUp.  It works, but 
> I can't clear the multiple setTimeouts triggered on each keyUp event.
> Example:
> 
>       $("input").keyup(function(){
>               var self = this;
>               var upd = setTimeout( function() {
>                       updateField( $(self) );  // function outside $ scope
to update field contents in dB
>               },6000);
>       });
> 
> I must've tried about 27 permutations of clearTimeout, 
> setting flag variables, nullifying variables, etc.  Nothing 
> has worked.
> 
> To be clear, I need to "restart the countdown" to update the 
> field if a user presses another key within 6 seconds of the 
> previous letter.  I'd rather not be shooting off POSTs on 
> every keystroke ;)

Reply via email to