[whatwg] Scripting Tweaks

On 4/20/05, Dean Edwards <dean at edwards.name> wrote:
> Ian Hickson wrote:
> > On Wed, 20 Apr 2005, Dean Edwards wrote:
> > I beg to differ:
> >
> >    elem[i].disabled = true;
> >    setTimeout(function () { elem[i].disabled = false }, 1);
> >
> > That looks a lot easier than the eval() to me. And shorter. And it will
> > have syntax errors caught at compile time.
> >
> 
> Yes, but as I said initially, that creates a closure. This is not always
> the most efficient solution. Your code won't work anyway because "i" is
> variable. The closure would need to be more complicated to work properly.

Talking about eval() and "efficient" should set off sirens in any JS
developer's mind. Using eval() requires re-compilation of the code at
runtime and is very rarely ever a real solution.

In addition, the proper argument to the setTimeout() function is a
function reference, not a string. If you have a basic understanding of
closures, they're not all that scary. Observe:

function fnMakeEnabled(oEl)
{
  return function() { oEl.disabled = false; };
}
...
for (...)
{
  elem[i].disabled = true;
  setTimeout(fnMakeEnabled(elem[i]), 1);
}

-- 
Brad Fults
NeatBox

Received on Wednesday, 20 April 2005 10:42:45 UTC