代码之家  ›  专栏  ›  技术社区  ›  TCCV

jsajax调用:需要睡眠,检查是否输入了更多字符然后执行

  •  1
  • TCCV  · 技术社区  · 16 年前

    我想做的是:

    1. 脚本检查3个以上字符
    2. 键入3个字符后,等待(可能使用setTimeout)
    3. 回路3和;4,直到1-2秒内不再输入字符
    4. ... 休息都准备好了。。。

    我的问题是:我知道我会怎么做,除了检查更多的字符进来。可能是这样的:

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

    那只是即兴的,可能不会马上就跑。无论如何,任何帮助,提示或指导都将不胜感激。

    1 回复  |  直到 16 年前
        1
  •  1
  •   Andres    16 年前

    每次html文本框回调调用wait方法时,都需要保留输入字符串的长度。

    如果当前字符串长度等于上一个长度,则在该间隔内没有添加任何字符,因此可以调用ajax,否则请继续等待

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