Difference between setTimeout with and without quotes and parentheses

前端 未结 6 1248
甜味超标
甜味超标 2020-11-22 07:06

I am learning JavaScript and I have learned recently about JavaScript timing events. When I learned about setTimeout at W3Schools, I noticed a strange figure wh

6条回答
  •  难免孤独
    2020-11-22 07:48

    What happens in reality in case you pass string as a first parameter of function

    setTimeout('string',number)

    is value of first param got evaluated when it is time to run (after numberof miliseconds passed). Basically it is equal to

    setTimeout(eval('string'), number)

    This is

    an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

    So samples which you refer are not good samples, and may be given in different context or just simple typo.

    If you invoke like this setTimeout(something, number), first parameter is not string, but pointer to a something called something. And again if something is string - then it will be evaluated. But if it is function, then function will be executed. jsbin sample

提交回复
热议问题