【问题标题】:setTimeout() method doesn't execute when using variables使用变量时 setTimeout() 方法不执行
【发布时间】:2011-05-02 00:46:32
【问题描述】:

我正在尝试编写一个函数,当您单击一个元素时,它会为它绘制一个底部边框。 该函数使用元素、最小宽度和最大宽度作为参数。 当我将它与 setTimeout() 一起使用来调用自身时,它不起作用。

如果我在 setTimeout() 中使用实际数字,它可以正常工作。 我找不到问题所在...

有人可以帮忙吗?

谢谢!

function drawBorder(elem,start_wid,end_wid)
{

//Checks if the header is in starting position.
//if it is - expend the width. If not decrease the width up to the starting
//position.
 if (elem.clientWidth <= start_wid)
  {
   increaseBorder(elem, end_wid);
  }
 else if (elem.clientWidth >= end_wid)
 {
  decreaseBorder(elem, start_wid);
 }
}


function increaseBorder(elem, end_wid)
 {
  elem.style.width=elem.clientWidth + 3 + "px";
  if (elem.clientWidth >= end_wid)
    {
     clearTimeout(timer2);
    }
  else {
    var str="increaseBorder(" + elem + ", " + end_wid + ");";            
    timer2=setTimeout(str,3);
 }
}

function decreaseBorder(elem, start_wid)
 {
  elem.style.width=elem.clientWidth - 3 + "px";
  if (elem.clientWidth <= )
   {
   clearTimeout(timer2);
   }
  else {
   var str="decreaseBorder(" + elem + ", " + start_wid + ");";
   timer2=setTimeout(str,3);
 }
}

【问题讨论】:

    标签: javascript animation settimeout


    【解决方案1】:

    您不能将元素的引用作为字符串传递。这个

    var str="increaseBorder(" + elem + ", " + end_wid + ");";
    

    会导致类似

    "increaseBorder([object ...], 100);"
    

    因为对象的默认字符串表示是[object &lt;Class&gt;]。甚至在计算字符串时会导致语法错误。

    从不将字符串传递给setTimeout。直接传一个函数:

    function increaseBorder(elem, end_wid) {
         elem.style.width=elem.clientWidth + 3 + "px";
         if (elem.clientWidth >= end_wid) {
             clearTimeout(timer2);
         }
         else {          
             timer2 = setTimeout(function(){
                 increaseBorder(elem, end_wid);
             }, 3);
         }
    }
    

    补充说明:

    您还应该修复其他错误,例如if (elem.clientWidth &lt;= ),并且您应该始终调用clearTimeout,以停止从其他函数开始的超时。

    【讨论】:

    • 非常感谢!我现在明白了。
    【解决方案2】:

    看起来函数 increaseBorderdecreaseBorder 没有全局声明。当它传递给setTimeout 的字符串时,它会在全局上下文中进行评估,这似乎是这里的问题。无需传递字符串,只需将函数传递给 setTimeout。

    var timer = setTimeout(function() {
        increaseBorder(elem, end_wid);
    }, 3);
    

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 2012-02-11
      相关资源
      最近更新 更多