繁体   English   中英

setTimeout,clearTimeout和javascript的复杂问题

[英]complex problem with setTimeout, clearTimeout, and javascript

我对Javascript不太了解,并且正在编写一个“自动结果”脚本,该脚本会在用户键入时自动获取的结果。 但是,由于PHP后端运行缓慢,因此我希望脚本检查自上次键入键以来是否已经过1秒。 这样,除非用户完成输入,否则不会调用PHP后端。 我的想法是使用setTimeout和clearTimeout处理此问题。 但是,我的脚本不起作用。 这是调用脚本的输入:

<input type="text" id="inputbox" onkeyup="lookup_input(this.value,0);" />

“ 0”是用于检查是否已设置超时的标志。 这是脚本:

var timeOut1;

function showQuery(input_myinput2) {    
    $.post("mybackendfile.php", {queryString: input_myinput2}, function(data){
        if(data.length >0) {
        $('#mydiv').html(data); //php backend stuff, don't worry about this
        }
    });
}               
function lookup_input(input_myinput,flag) {
    if(input_myinput.length == 0) {
        $('#mydiv').hide(); //check to see if there is an input, and if not, hide the div that displays autoresults
    } 
    else {   
              //the flag checks to see if the Timeout has been set

        if(!flag) { 
            timeOut1 = setTimeout(function(){showQuery(input_myinput)}, 1000);
            //change the flag to "1" so that if another key is pressed it will throw the else statement, and if the key is pressed soon enough, it will clear the Timeout
            $('#inputbox').onkeyup('lookup_input(this.value,1)');       
            $('#mydiv').show();
            $('#mydiv').html('Searching... ');
        }
        else { //if timeout has been set then and next key has been pressed
            clearTimeout(timeOut1);
            $('#mydiv').html('Searching... ');
            timeOut1 = setTimeout(function(){showQuery(input_myinput)}, 1000);  
        }
    }
} 

关于如何正确访问showQuery函数以及如何使此脚本工作的任何建议? 另外,除了使用setTimeout / clearTimeout以外,还有其他建议可以进行自动结果停止吗? 谢谢!

Underscore.js提供了一个简洁的debounce功能,可以抽象化此(通常是必需的)功能。

看看带注释的源代码如何实现。

您真的不需要标志。 事件处理程序应始终清除超时并开始新的超时。

现在的方式是为输入元素添加另一个冗余事件处理程序。

我也想你应该移动代码,显示“搜索...”消息超时代码里面 ,因为它会是一个有点误导,以显示?1秒钟你其实并开始搜索之前。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM