开发者

complex problem with setTimeout, clearTimeout, and javascript

I am a bit of a noob at Javascript and am writing an "autoresult" script that automatically gets the results of an as the user is typing. However, because the PHP backend is slow, I want the script to check and see if it has been 1 second since the last keyup. That way, the PHP backend won't be called unless the user is done typing. My idea was to use setTimeout and clearTimeout to handle this. However, my script doesn't work. Here is the input that calls the script:

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

"0" is a flag used to check whether a Timeout has been set. Here is the script:

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
    } 
    e开发者_运维技巧lse {   
              //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);  
        }
    }
} 

any suggestions on how to access the showQuery function correctly and how to get this script to work? also, any suggestions on another way to do the autoresult stall besides using setTimeout/clearTimeout? thanks!


Underscore.js provides a neat debounce function that abstracts away this (often needed) feature.

Take a peek at the annotated source code on how it is implemented.


You really don't need the flag. The event handler should always clear the timeout and start a new one.

The way you've got it now, you're adding another, redundant event handler for the input element.

I also think you should move that code that shows the "Searching..." message to inside the timeout code, because it'd be a little misleading to show it 1 second before you actually do start searching.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜