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
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.