Difference between setTimeout with and without quotes and parentheses

前端 未结 6 1299
甜味超标
甜味超标 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:32

    With the parentheses:

    setTimeout("alertMsg()", 3000); // It work, here it treat as a function
    

    Without the quotes and the parentheses:

    setTimeout(alertMsg, 3000); // It also work, here it treat as a function
    

    And the third is only using quotes:

    setTimeout("alertMsg", 3000); // It not work, here it treat as a string
    

    function alertMsg1() {
            alert("message 1");
        }
        function alertMsg2() {
            alert("message 2");
        }
        function alertMsg3() {
            alert("message 3");
        }
        function alertMsg4() {
            alert("message 4");
        }
    
        // this work after 2 second
        setTimeout(alertMsg1, 2000);
    
        // This work immediately
        setTimeout(alertMsg2(), 4000);
    
        // this fail
        setTimeout('alertMsg3', 6000);
    
        // this work after 8second
        setTimeout('alertMsg4()', 8000);

    In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.

提交回复
热议问题