setTimeout(code,millisec)
setTimeout() 只執行 code 一次。如果要多次呼叫,請使用 setInterval() 或者讓 code 自身再次呼叫 setTimeout()。
例項:
<html> <head> <script type="text/javascript"> function timedMsg() { var t=setTimeout("alert(`5 seconds!`)",5000) } </script> </head> <body> <form> <input type="button" value="Display timed alertbox!" onClick="timedMsg()"> </form> <p>Click on the button above. An alert box will be displayed after 5 seconds.</p> </body> </html>
clearTimeout() 方法可取消由 setTimeout() 方法設定的 timeout。
語法:
clearTimeout(id_of_settimeout)
例項:
<html> <head> <script type="text/javascript"> var c=0 var t function timedCount() { document.getElementById(`txt`).value=c c=c+1 t=setTimeout("timedCount()",1000) } function stopCount() { clearTimeout(t) } </script> </head> <body> <form> <input type="button" value="Start count!" onClick="timedCount()"> <input type="text" id="txt"> <input type="button" value="Stop count!" onClick="stopCount()"> </form> </body> </html>