【问题标题】:calling a function in javascript after a period of time has passed经过一段时间后在javascript中调用函数
【发布时间】:2011-04-12 00:31:32
【问题描述】:

我正在尝试编写一个函数,该函数会在用户输入输入字段时自动提示用户的意思。现在我已经完成了所有自动建议代码,但是在我的 javascript 中,无论我做什么,我都无法在 toggleGenusInput 中进入第一个(如果通过 php 查询数据库并获取建议,则首先)。

有谁知道我可以如何修改我的代码,以便如果在输入字段中输入了某些内容并且在 2 秒后没有更改,那么它将首先输入该内容吗?谢谢。

这是我的脚本全局变量:

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

这是连接到输入节点的 onfocus 方法的函数:

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();
        }
    }
}

这是函数附加到的 html 对象:

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

【问题讨论】:

  • @sje397,感谢您向我展示了这一点。但是,在这个程序中,我需要连续调用该超时函数(因此,无论给出什么函数,都需要每 2 秒调用一次)。有没有办法做到这一点?
  • setInterval 几乎一样,但是会重复调用你指定的代码,直到你发出'clearInterval'。
  • 你看过网络上的自动提示脚本吗?大多数优秀的已经做了你想做的一切。

标签: javascript html ajax dom


【解决方案1】:

您可以改用setTimeout 并将处理程序绑定到keyup 事件:

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);
    }
}

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

现在,只要按下某个键(不在焦点上),就会调用您的函数并等待一段时间以执行该功能。如果另一个超时正在运行,它将首先被取消(否则您将在用户插入文本时一遍又一遍地创建超时,这会导致奇怪的结果)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2017-08-23
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多