开发者

calling a function in javascript after a period of time has passed

I'm trying to write a function that will auto suggest what the user means when they type into an input field. Right now I have all of the auto suggest code complete but in my javascript I can't get to the first if in toggleGenusInput no matter what I do (this first if queries the database through php and gets the suggestions).开发者_开发问答

Does anyone know how I could modify my code so that if something is typed in the input field and is not changed after 2 seconds it will enter that first if? Thanks.

Here are my script globals:

var time = new Date();
var timeout = 2000; //query db every 2 seconds of not typing anything
var autoSuggest = true;
var lastQueryTyped = "";
var queryTypedAt = time.getTime(); //what time the last new text was entered

Here's the function that's connected to an input node's onfocus method:

function toggleGenusInput(inputNode) {
    if(autoSuggest) {
        if((time.getTime() - queryTypedAt) >= timeout && inputNode.value == lastQueryTyped) {
            //the input has not changed and it's reached the timeout time, requery the db

            responseDoc = getXMLFrom("getsimilaritems.php?query=" + inputNode.value);

            if(queryFindsSuggestions(responseDoc)) {
                cleanUpSuggestions();
                appendSuggestions(inputNode, responseDoc);
            }
        }
        else if(inputNode.value != lastQueryTyped) {
            //something new was entered so update the time and what was put in

            lastQueryTyped = inputNode.value;
            queryTypedAt = time.getTime();
        }
    }
}

And here's the html object that function is attached to:

<input type="text" name="autoSuggestInput" onfocus="toggleGenusInput(document.myForm.autoSuggestInput)" />


You could use setTimeout and bind the handler to the keyup event instead:

function toggleGenusInput(inputNode) {
    if(autoSuggest) {
        if(_timeout) {
           clearTimeout(_timeout);
        }
        _timeout = setTimeout(function() {
            //the input has not changed and it's reached the timeout time, requery the db 
            responseDoc = getXMLFrom("getsimilaritems.php?query=" + inputNode.value);

            if(queryFindsSuggestions(responseDoc)) {
                cleanUpSuggestions();
                appendSuggestions(inputNode, responseDoc);
            }

        }, 2000);
    }
}

and

<input type="text" name="autoSuggestInput" onkeyup="toggleGenusInput(document.myForm.autoSuggestInput)" />

Now whenever a key is pressed (not on focus), your function will be called and wait a certain time to execute the functionality. If another timeout is running, it will be canceled first (otherwise you would keep creating timeouts over and over again while the user inserts text which would lead to strange results).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜