views:

39

answers:

1

Hi All,

I have an app that includes a search feature. This feature is implemented by having a user type a term in a search bar. Once the user enters 3 characters an ajax call is started. I thought that this would be enough, but it turns out that there's a bug that I think has to do with timing and the fact that several ajax calls can be done in quick succession by just typing a search term over 4 characters.

What I would like to do is this:

  1. User starts typing
  2. script checks for 3+ characters
  3. once 3 characters are typed, wait (using setTimeout perhaps)
  4. once timeout is reached, check if more characters have been entered
  5. loop 3 & 4 until no more characters have been entered for 1-2 seconds
  6. do ajax call ... rest is all set ...

my question: I know how I would do everything except check for more characters coming in. maybe something like this:

var searchTerm;
function wait(userInput){
   if(userInput.length < 3){return 0;}
   searchTerm = userInput;
   setTimeout(function(){checkInput(userInput);}, 1000);
}

function checkInput(userInput){
   if (userInput == searchTerm){
      ... do AJAX call ...
   } else {
      return 0;
   }
}

That's just off the cuff and probably wouldn't run right away. Anyways, any help, tips or direction would be greatly appreciated.

Thanks, Tim

+1  A: 

You need to keep the length of your entered string every time your wait method is called by the html textbox callback.

If the current string length is equal to the previous length, no characters were added at that interval so you can call the ajax, otherwise keep waiting

    var timerHandle = null;
    var currLen = 0;
    function wait(userInput)
    {
        currLen = userInput.length;
        if(currLen < 3)
        {
            return 0;
        }

        if(timerHandle)
        {
            clearTimeout(timerHandle);
            timerHandle = null;
        }
        timerHandle = setTimeout(function(){checkInput(userInput);}, 1000);
    }


function checkInput(userInput)
{
    timerHandle = null;
    if (currLen == userInput.length)
    {
      ... do AJAX call ...
    } else {
      return 0;
   }
}   
Andres
Thank you Andres. If I understand you correctly, then the snippit I posted would be a good starting point, right? The var searchterm would keep the latest search term the user input, then after 1 second it checks to see if they're the same... At least that's my understanding. Am I understanding something wrong, though?
Tim
I edited the answer and put some code that reflects what I was thinking. I also changed a bit the way setTimeout works, if Timeout is called again in the 1sec interval, I cancel the last call. Apart from that, what is going wrong in the code you supplied?
Andres
bingo. I am still looking at that timerHandle variable, but it works. Thank you very much.
Tim