<html> <body> <script> function delayFunction() { //display the message on web after 3 seconds on calling delayFunction document.write('<h3> Welcome to lidihuo <h3>'); } </script> <b> Example of delay the execution of function <b> <p id="t1"></p> <button onclick = "setTimeout(delayFunction, 3000)"> Click Here </button> </body> </html>
<html> <body> <script> function waitAndshow() { //define a date and time variable var systemdate = new Date(); //display the updated time after every 4 seconds document.getElementById("clock").innerHTML = systemdate.toLocaleTimeString(); } //define time interval and call user-defined waitAndshow function setInterval(waitAndshow, 4000); </script> <h3> Updated time will show in every 4 seconds </h3> <h3> The current time on your computer is: <br> <span id="clock"></span> </h3> </body> </html>
输出
在执行上述代码时,响应将是一个简单的HTML语句,没有任何时间字符串,如下所示:
4秒钟后,JavaScript函数将调用并开始显示时间。这将每隔四秒重复显示您的系统时间。
示例
setInterval()方法的另一个示例,用于在每4秒连续显示一次消息字符串。
<html> <body> <script> function waitAndshow() { //display the message on web on calling delayFunction document.write('<h3> Welcome to lidihuo <h3>'); } </script> <h3> A string will show in every 4 seconds </h3> <!-- call user-defined delayFunction after 4 seconds --> <button onclick = "setInterval(waitAndshow, 4000)"> Click Here </button> </body> </html>