0

当我使用此代码时,它不会在从 jQuery 成功返回时激活 setTimeout

function waitForEvents(last_id){
$.ajax({
            type: "GET",
            url: "/functions/ajax.php?func=feed&old_msg_id="+last_id,

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){
                var json = jQuery.parseJSON(data);
                if(json !== 'null') {
                $.each(json.earnings, function (index, value) {
                     $('#feed').append(value);
                });
                var old_msg_id = json['last_id'];
                }
                alert("working");
                setTimeout('waitForEvents(last_id)',"1000");  
            },

            error: function (XMLHttpRequest, textStatus, errorThrown){
                alert("Error:" + textStatus + " (" + errorThrown + ")");
                setTimeout('waitForEvents(last_id)',"15000");       
            },
});
};

知道为什么因为它实际上正在返回(数据)所以它正在处理响应而不是再次激活 settimeout

4

2 回答 2

1

您的 setTimeout 方法没有传递函数(显然作为字符串很好:/)

setTimeout(function() { waitForEvents(last_id); }, 15000);
于 2013-02-10T15:43:10.560 回答
0

您传入的字符串在全局范围内setTimeout进行评估。我的猜测是您的函数没有在全局范围内定义,或者在全局范围内没有定义值。last_id

如果您的目标是重用last_id传递给函数的参数,请将您的setTimeout调用更改为:

setTimeout(function() {
    waitForEvents(last_id);
}, 1000); // Or 15000 for the other call

(另请注意,第二个参数应该是数字,而不是字符串。)

这是我在全局范围内评估字符串的意思的示例:

(function($) {

  $("#target").click(function() {
    setTimeout(foo, 500);
    setTimeout("bar()", 500);
    display("Timers started");
  });

  function foo() {
    display("foo called");
  }

  function bar() {
    display("bar called");
  }

  function display(msg) {
    $("<p>").html(String(msg)).appendTo(document.body);
  }

})(jQuery);

实例| 来源

假设您有一个带有 的元素id "target"并单击它,半秒钟后您会看到“foo called”出现在页面上,但您不会看到“bar called”。如果您使用任何现代浏览器,您将在 JavaScript 控制台中看到一条错误消息,指出bar未定义。那是因为没有全局函数被调用bar,包装函数中只有一个函数被调用bar。所以字符串版本失败。

setTimeout尽可能避免将字符串传递给。这总是可能的。(向达赖喇嘛道歉。)

于 2013-02-10T15:51:59.790 回答