开发者

setTimeout() method doesn't execute when using variables

开发者 https://www.devze.com 2023-03-01 18:32 出处:网络
I am trying to write a function that draws a bottom border for an element when you click it. The function uses the element, minimum width, and maximum width as parameters.

I am trying to write a function that draws a bottom border for an element when you click it. The function uses the element, minimum width, and maximum width as parameters. When I use it with the setTimeout() to call itself it doesn't work.

If I use actual numbers in the setTimeout() it works fine. I couldn't find what's the problem...

Anyone can help?

Thank you!

function dr开发者_运维知识库awBorder(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);
 }
}


You cannot pass a reference to an element as a string. This

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

will result in something like

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

as the default string representation of an object is [object <Class>]. It would even result in a syntax error when the string is evaluated.

Never pass a string to setTimeout. Pass a function directly:

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);
     }
}

Further notes:

You should also fix your other errors, like if (elem.clientWidth <= ) and you should always call clearTimeout, to also stop timeouts started from the other function.


It looks like the functions increaseBorder and decreaseBorder are not declared globally. When a string it passed to setTimeout, it is evaluated in the global context, which appears to be the problem here. Instead of passing a string, just pass a function to setTimeout.

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

精彩评论

暂无评论...
验证码 换一张
取 消