SetTimeout and SetInterval use eval therefore are evil

Eval is evil. Ok, it's not like it goes out at night and kill kittens but it is evil nevertheless.

Let's start from the least evil to the kitten killer.

  1. Code passed through the eval compiler is run in a global namespace. When you pollute the global namespace there is high chances that your variables will collide and it makes it much harder to debug your code.
  2. Eval is not friendly to debugging. When there is an error, there is no line number because, well the code is generated on the fly. Some compiler may give you the line number based on the string that was evaluated as code, but if the string is a variable, that's another extra step to find out where exactly.
  3. The code cannot be optimized because, well the code is not known until it is executed.
  4. Your code might run slower because it has to create a new instance of JavaScript interpreter to run.
  5. It opens up your code to injection attacks.

With all this said, eval can be used properly. But there are always better alternatives that can be written without having to resort to it. One example I saw recently.

var rand = Math.floor(Math.random()*100);
eval('var win'+rand+' ="url","page_'+rand+'",...)');

What the user wanted to do was to have separate windows opened every time a button is clicked. What if he just used it like this:

var rand = Math.floor(Math.random()*100);"url","page_"+rand,...);

Ok enough about Eval and its evils, I hope you are convinced not to use it.

setTimeout and setInterval, I call them SetEvil

setTimeout and setInterval are timed functions. They are both used to run a function at a future time. With setInterval it runs the function at intervals. I will only show setTimeout in the example but they work the same way.

setTimeout("eval code here",timer);

The first argument is a string, you actually pass it some JavaScript that will be evaluated at a global namespace when the timer expires. Read the evils of evals again above and then come back. The good thing is that you are not required to pass in a string of JavaScript code. The same function can take a function as it's first argument. Note that it is also much more efficient to call a function than parse a string, run the JavaScript interpreter an then run the code.

setTimeout(function () {
    // nice fast code here
},2000); // run after 2 seconds

Here is how you use it in a real life situation:

function fade(element) {
    var op = 1;  // initial opacity
    var timer = setInterval(function () {
        if (op <= 0.1){
   = 'none';
        } = op; = 'alpha(opacity=' + op * 100 + ")";
        op -= op * 0.1;
    }, 50);

So the lesson here is, don't use a string as a argument for setTimeout or setInterval. JavaScript will evaluate it using eval. The best approach is to use a function, named or anonymous.


There are no comments added yet.

Let's hear your thoughts

For my eyes only