I wrote a code in JavaScript shown below: in this code, onClick button wants to call function fadetext()
, and the function fadetext()
itself setTimeout.
hex = 255 // Initial color value. function fadetext() { if (hex > 0) { //If color is not black yet hex -= 11; // increase color darkness document.getElementById("sample").style.color = "rgb(" + hex + "," + hex + "," + hex + ")"; setTimeout(fadetext, 20); } else hex = 255 //reset hex value }
<div id="sample" style="width:100%"> <h3>John slowly faded into view</h3> </div> <button onClick=fadetext()>Fade Text</button>
However, when I refer to the answer, the differences are shown in the following two lines of codes:
setTimeout("fadetext()",20);
Another one is:
<button onClick="fadetext()">Fade Text</button>
Could somebody helps me to explain why this also works?
setTimeout
takes a reference to a function that should be called when the timeout expires, not a string.
Although setTimeout
can take a string that is eval
d, do not use it , it's a security risk in the same way that eval()
is.
setTimeout("fadetext()",20);
should be setTimeout(fadetext,20);
and the onclick
attribute is all lowercase.
<button onClick="fadetext()">Fade Text</button>
should be <button onclick="fadetext()">Fade Text</button>
var hex = 255 // Initial color value. function fadetext() { if (hex > 0) { //If color is not black yet hex -= 11; // increase color darkness document.getElementById("sample").style.color = "rgb(" + hex + "," + hex + "," + hex + ")"; setTimeout(fadetext, 20); } else hex = 255 //reset hex value }
<div id="sample" style="width:100%"> <h3>John slowly faded into view</h3> </div> <button onclick="fadetext()">Fade Text</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.