1

我的代码看起来像:

$(document).ready(function(){
    var cont = 0;

    function func1(cont)
    {
        //Some code here
        search.setSearchCompleteCallback(this, searchComplete, null);
        //Some other code
    }
    func1(cont);

    function searchComplete()
    {
        //Some code
        cont += 1;
    if (cont < length ) {
    func1(cont);
    } else {
            // Other code
    }
    }
});

所以我想做的是延迟 func1(cont); 的执行。在 searchComplete() 函数内部。这样做的原因是所有代码都是为了与 Google 搜索 API 和 PageRank 检查一起工作,我需要放慢脚本速度,以免被禁止。(特别是对于它提出的关于 PR 检查的请求)。如果我只是在 func1(cont) 上使用 setTimeout(); 它说没有定义 func1(),如果我尝试在 $(document).ready() 之外获取函数,它会看到该函数,但 Google 代码不会因为它需要完全加载页面。

如何修复 setTimeout 或如何将脚本暂停几秒钟?

谢谢!

4

4 回答 4

5

func1(cont);

作为

window.setTimeout(function() {
    func1(cont);
}, 1000);
于 2009-09-07T17:27:19.173 回答
1

而不是像这样声明函数:

function func1(cont) {}

像这样声明它:

var func1 = function(cont) {}

您需要稍微重新排列您的代码:

$(document).ready(function(){
    var cont = 0;
    var func1;

    var searchComplete = function()
    {
        //Some code
        cont += 1;
        if (cont < length ) {
            func1(cont);
        } else {
                // Other code
        }
    }

    func1 = function(cont)
    {
        //Some code here
        search.setSearchCompleteCallback(this, searchComplete, null);
        //Some other code
    }

    func1(cont);
});
于 2009-09-03T20:32:39.423 回答
0

我会尝试这样的事情。我更喜欢在 jquery 命名空间内声明变量和函数,但您同样可以将 cont 变量和函数移到文档就绪函数之外,并使它们全局可用。

$(document).ready(function(){
    $.cont = 0;
    $.func1 = function() {
        //Some code here
        search.setSearchCompleteCallback(this, $.searchComplete, null);
        //Some other code
    }

    $.searchComplete = function() {
        //Some code
        $.cont += 1;
        if (cont < length ) {
            setTimeout($.func1,1000);
        } else {
            // Other code
        }
    }

     setTimeout($.func1,1000); // delay the initial start by 1 second
});
于 2009-09-04T00:50:37.313 回答
0

希望我的描述正确:

  • document.ready() 事件触发
  • 在 document.ready() 中,您希望在 X 毫秒后调用一个函数
  • 此函数将 Google 对象 search.setSearchCompleteCallback() 连接到另一个函数(看起来它需要来自 的父对象this

如果是这种情况,为什么需要在 document.ready() 范围内声明的任何函数?您不能简单地将所有 3 个全局化吗?例如

var search = null; // initialise the google object
var cont = 0;

function timedSearch()
{
  search.setSearchCompleteCallback(this, searchComplete, null);
}

function searchComplete()
{
   if (++cont < length) // postfix it below if this is wrong
       setTimeout(timedSearch,1000);
}

$(document).ready(function()
{
   setTimeout(timedSearch,1000);
}

如果我误解了,请给我投反对票。

于 2009-09-07T17:18:26.897 回答