如何在setTimeout调用中解决Var超出范围的问题 [英] How to solve Var out of scope within setTimeout call
本文介绍了如何在setTimeout调用中解决Var超出范围的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在setInterval回调中调用setTimeout:
I am trying to call a setTimeout from within a setInterval callback:
function callback()
{
//assign myVar
var myVar = document.getElementById("givenID");
//...
//now wait 2 secs then call some code that uses myVAr
setTimeout("myVar.innerHTML = 'TEST'", 2000);
}
setInterval("callback();", 10000);
setInterval按预期工作但setTimeout调用失败。我想这个问题与我引用一个不在范围内的变量(myVar)有关。
setInterval works as expected but setTimeout call is failing. I guess the problem is related to the fact that I am referencing a variable (myVar) that's not in scope.
解决这个问题的最佳方法是什么?
What's the best way to solve this?
推荐答案
这是关闭的理想候选人:
This is a perfect candidate for closures:
setInterval(
function ()
{
var myVar = document.getElementById("givenID");
setTimeout(
function()
{
// myVar is available because the inner closure
// gets the outer closures scope
myVar.innerHTML = "Junk";
},2000);
}, 10000);
你的问题与范围有关,这可以解决这个问题。
Your problem is scope related, and this would work around that.
这篇关于如何在setTimeout调用中解决Var超出范围的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文