Day #3 Pro Tip #Javascript

Do not pass strings, to setTimeout() and setInterval(). Pass a variable referencing a function…

Manjula Dube
Geekabyte

--

If you pass a string into setTimeout() or setInterval(), the string will be evaluated the same way as with eval, which is slow. Also eval is usually evil for several reason in javascript :)

Note: Every time you have to evaluate a string, you fire up a full compiler. For each and every invocation whereever needed

Below example works, but it is not the generally accepted syntax for setTimeout.

Instead of using…

setInterval('CallMe()', 1000);  
setTimeout('CallMeAfterNineSeconds()', 9000);

Use the below instead…..

setInterval(CallMe, 1000);  
setTimeout(CallMeAfterNineSeconds, 9000);
// CallMe is a variable referencing a function
// CallMeAfterNineSeconds is a variable referencing a function

Thanks for reading!!

Stay tuned for more Javascript learnings :)

--

--

Manjula Dube
Geekabyte

Senior Developer, Javascript Lover, Frontend Technology, Passion is to learn and share.