如何在 setTimeout 调用中解决 Var 超出范围 [英] How to solve Var out of scope within setTimeout call

查看:17
本文介绍了如何在 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?

推荐答案

这是闭包的完美候选:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆