In my line of work, I edit a lot of legacy code, and with that I see a lot of the following:
For those who don’t know (and would like to learn), setTimeout (and its sister, setInterval) can accept a string of code to be executed as an argument. Know what other method takes a string of code and executes it? eval() does. Generally, methods like these should be avoided, as they leave ways for arbitrary scripts to run if you’re not careful.
So how could the above code be improved? Take the following:
But what about my arguments?
Yes, you can still pass arguments with this form. Whereas before you’d make up a whole string to be executed, you’d now just run it with an anonymous function. For those of you using jQuery, this should feel very familiar: