2012-08-10 248 views
3

我正在运行一个函数来检查数据库条目是否存在。clearInterval在一种情况下失败,但在另一种情况下失败

在我的网页加载我检查元素是否存在,如果是这样我用setInterval运行功能。像这样:

if ($('#encoding').length) { 

    console.log("auto_update start"); 
    var update = setInterval(auto_update, 12000); 
} 

然后在我auto_update功能发生这种情况

function auto_update() { 

    console.log("auto_update running"); 

    $.ajax({ 
     type: 'POST', 
     url: ajaxurl, 
     data: { 
      action: "dhf_ajax_router", 
      perform: "dhf_check_status", // the function we want to call 
      post_id: $('#post_id').val(), 
      nonce: $('#dhf-video-meta-nonce').val() 
     }, 
     success: function(response) { 

      if (response === "continue") { 

       console.log("still encoding"); 

      } else { 

       clearInterval(update); 
       console.log("complete " + response); 
      } 
     } 
    }); 
} 

的问题是,如果$('#encoding')不存在在开始页面上,并通过用户手动内触发:

$(document).on("click", ".run_encode", function(){ 

     // doing the necessary stuff here. 
     if (response === "sent") { 

       // more stuff 
       var update = setInterval(auto_update, 12000); 
     } 

}); // end .run_encode 

然后clearInterval(update)不起作用,它结束了一个无限循环。

我想不出为什么。在两种情况下都设置了名称为update的间隔,那么为什么在第二种情况下清除它不起作用?

+0

关键词:“JavaScript的变量范围” – 2012-08-10 07:23:13

回答

2

您必须确保共享变量update是在这两个范围内有效。这意味着它或者需要在一个共同的父范围内,或者您需要使变量成为全局变量,因此它不会超出范围。

最有可能的是,您声明的update位于终止函数中,当该函数终止时,update变量超出范围并被销毁。

您可以进行变量的初始设置进入全球范围内(所以它仍然是可用的,当你调用clearInterval()这样的:

$(document).on("click", ".run_encode", function(){ 

    // doing the necessary stuff here. 
    if (response === "sent") { 

      // more stuff 
      window.update = setInterval(auto_update, 12000); 
    } 

}); // end .run_encode 

或者,你可以只声明update变量是全球性的,通过首先将这一在全局级别(任功能外),然后这个代码将只修改全局变量:

var update; 

$(document).on("click", ".run_encode", function(){ 

     // doing the necessary stuff here. 
     if (response === "sent") { 

       // more stuff 
       update = setInterval(auto_update, 12000); 
     } 

}); // end .run_encode 
+0

感谢您的,我使用的第二示例J最糟糕的问题是,这是一种有效的做事方式,还是我最好拥有某种路由器功能来连续调用所有东西? – deadlyhifi 2012-08-10 11:18:55

+0

@deadlyhifi - 在一段时间内“轮询”你的服务器,直到它告诉你它已经完成是没有效率的。你没有解释你实际想要解决的问题,所以我不知道如何最好地推荐更好的解决方案。 – jfriend00 2012-08-10 13:57:18

+0

我正在向Zencoder发送一个请求以对视频文件进行编码。当我发送它时,我在数据库中设置了一个标志来表示它是编码。完成后,Zencoder发送一个回调,删除该标志并填充其他数据(如编码文件的位置)。我正在轮询数据库以查看该标志是否消失。如果它有,那么我会得到新的数据并将其放在页面上。 – deadlyhifi 2012-08-10 14:37:32

4

你声明函数内部update变量。另一个函数不能访问它的值。

jfriend00就如何解决它广泛的答案。我会采取另一条路线:使用setTimeout。无论如何,建议您这么做,因为AJAX调用并不是一个固定的时间,而是每次都会变化。想象一下,由于网络问题,它需要12秒以上:你会被搞砸。

相关问题