Why do people use setTimeout ("func ()", ...) instead of setTimeout (func, ...)

I see that this is being used a lot, and I was told that the function reference between the quotation marks was bad, because setTimeout / setInterval evals reference. What is the actual difference between the two such that one is used over the other and why do I see that it is used so often, although it should be generally known that this method is bad?

+4
source share
3 answers
  • People may not understand that they can use an unspecified form.

  • The name specified in the string is not yet defined.

  • The given form gives you delayed execution:

     setTimeout("myFunction(1, 'hello')", 100) 

    easier to understand than:

     setTimeout(function () { myFunction(1, 'hello') }, 100) 

    and this does not do what the author wants:

     setTimeout(myFunction(1, 'hello'), 100) 
+3
source

There are two main differences between these two forms:

 setTimeout("myFunc()", 100); 

and

 setTimeout(myFunc, 100); 

The first is less efficient and evaluates a function in the global scope, so you cannot pass it a local function or any function that is not global.

To look at the efficiency argument, if you want to call a function that you had in your code, you would write:

 x = myFunc(); 

or write:

 x = eval("myFunc()"); 

Of course, you should write the first, because:

  • As usual you write javascript
  • A function reference can be resolved once in the first pass of the interpreter, and not every time it executes
  • Minifiers / optimizers can rename your character first, but not second.
  • You can call local functions from the first, and the second requires a global function
  • eval() is a pretty heavy thing that should only be used when there is no other better way to do this.

FYI, this jsPerf comparison shows that the eval() version is 96% slower. In some cases, performance may not matter, but you can understand how less effective it is.

+1
source

I am sure that this also prevents memory leak.

Does not flow X:

 var x = $("loading"); setTimeout("createTree(1);", 0); 

Leak X:

 var x = $("loading"); setTimeout(function(){createTree(1);}, 0); 
0
source

All Articles