【问题标题】:Javascript:how to make setTimeout not delay for the first execution?Javascript:如何使 setTimeout 不延迟第一次执行?
【发布时间】:2016-02-13 01:36:34
【问题描述】:

我建立了一个类似于谷歌搜索的即时搜索功能。一个 setTimeout 函数用于去抖动/限制搜索。但是,我不希望第一次执行 searchq() 函数的延迟。如何修改代码来实现这一点?

var timeout = null;

function doDelayedSearch(txt) {

          if (timeout) {  
            clearTimeout(timeout);
          }

            timeout = setTimeout(function() {
                searchq(txt); //this is the search function (posting and fetching result)
                }, 1000);
}

function searchq(txt){
        // get the value
            // txt = $("input").val();
            // post the value
            if(txt){
                $.post("search.php", {searchVal: txt}, function(result){
                    $("#search_output").html(result+"<br><a class='anchor_tag_s' href='createobject.php?object="+txt+"'><div id='notfound'>Not found above? Create Here.</div><a>");
                });
            }
            else{
                $("#search_output").html("");
            }
        };

【问题讨论】:

  • 顺便说一句,请注意您不需要if (timeout),您可以直接拨打clearTimeout()。您的 if 条件 每次 都会为真,除非第一次调用 doDelayedSearch(),因为 timeout 永远不会被设置回假值。使用 null 值或使用已完成或取消超时的 id 调用 clearTimeout() 没有任何害处。

标签: javascript jquery html search


【解决方案1】:

简单,

设置超时后调用函数
编辑:当还没有超时时调用该函数

function doDelayedSearch(txt) {

          if (!timeout) {
            searchq(txt); // the first time is the only time, there is no timeout
          }
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                searchq(txt); //this is the search function (posting and fetching result)
                }, 1000);
}

【讨论】:

  • 但是每次调用doDelayedSearch()时总是会调用两次。
  • @nnnnnn 有正确的线索:你的 if 条件每次都会为真......除了第一次
【解决方案2】:

试试:

function doDelayedSearch(txt) {
    clearTimeout(timeout); // clearTimeout(null) will not throw.
    timeout = setTimeout(function() {
        searchq(txt);
    }, timeout ? 1000 : 0); // if timeout is null, then call with minimum delay, otherwise one second. 
}

这样,searchq() 总是从 setTimeout() 调用,但当timeout 仍然为空时,第一次调用有特殊情况。

【讨论】:

    【解决方案3】:

    你可以作弊并设置一个全局变量。

    global.firstExecution = true;
    
    if (global.firstExecution == true) {
        searchq(txt);
    }
    else {
        var timeout = setTimeout(function() {
            searchq(txt); //this is the search function (posting and fetching result)
        }, 1000);
    }
    

    然后在你的函数中说:

    global.firstExecution = false;
    

    这不是一个迷人的解决方案,但它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      相关资源
      最近更新 更多