Frage

Can someone please explain to me what is wrong with my code below? I am declaring a public variable and setting it to a setTimeout, and if not null, clearing the timeout before it gets set again. When I try to clear the timeout I get undefined so the timeout continues to run.

var usernameCheckTimeout = null;

$(document).ready(function(){
    $("#username").on("keyup", function(e){ 
        if($(this).val().length >= 6)
        {
            if(usernameCheckTimeout != null)
            {
                clearTimeout(usernameCheckTimeout);
            }
            usernameCheckTimeout = setTimeout(isUsernameAvailable($(this).val()), 1000);
        }
    });
});

function isUsernameAvailable(username)
{
    $.ajax({
        url : "/account/username-check",
        method : "POST",
        dataType : 'json',
        data : {
            'username' : username
        }
    }).done(function(data) {
        console.log(data);
    });
};
War es hilfreich?

Lösung 2

The timeout is being cleared. The problem is that you are calling your function immediately instead of passing the function to setTimeout.

setTimeout(isUsernameAvailable($(this).val()), 1000);

isUsernameAvailable($(this).val()) will be called and the result of this call will be passed to setTimeout.

You should instead pass a function which calls this function:

EDIT: As @Mark said, you also need to deal with this not being what you expect:

var value = $(this).val();

setTimeout(function(){
    isUsernameAvailable(value)
}, 1000);

Andere Tipps

You do not need to do the null check also you need to create a closure around this, otherwise this will refer to not what you think this actually is.

var usernameCheckTimeout;
$("#username").on("keyup", function (e) {
    if ($(this).val().length >= 6) {
        clearTimeout(usernameCheckTimeout);
        var that = this;
        usernameCheckTimeout = setTimeout(function () {
            isUsernameAvailable($(that).val();
        }, 1000);
    }
});

Some jsfiddle love like usual.

You have a couple of issues. The first issue, which is huge, is that you are executing isUsernameAvailable($(this).val()) immediately and passing the return value to setTimeout - you need to move this into an anonymous function so it does not execute until the anonymous function is called by the timeout:

usernameCheckTimeout = setTimeout(function () {
    isUsernameAvailable($(this).val());
}, 1000);

the javascript timeout functions rely on numeric IDs to function. You should avoid testing for null or undefined or anything else, and instead test for a number:

// leave it as undefined
var usernameCheckTimeout;

...

if (typeof usernameCheckTimeout === 'number') {
    clearTimeout(usernameCheckTimeout);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top