setInterval() definition and usage
The setInterval() method executes a function or expression in a specified period (in milliseconds). This method will keep calling the function until clearInterval() is used to explicitly stop the function or window being closed. The parameter of the clearInterval() function is the ID value returned by setInterval().
grammar
setInterval(code,millisec[,"lang"])
code required. The function to be called or the string of code to be executed.
millisec must. The interval between periodic execution or calling code, in milliseconds.
Return value
A value that can be passed to Window.clearInterval() to cancel periodic execution of the code.
Example of usage:
The code copy is as follows:
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<input type="text" id="clock" size="35" />
<script language=javascript>
var int=setInterval("clock()",50);
function clock(){
var t=new Date();
document.getElementById("clock").value=t;
}
</script>
</form>
<button onclick="window.clearInterval(int)">
Stop interval event</button>
</body>
</html>
setTimeout() definition and usage
The setTimeout() method is used to call a function or calculate an expression after a specified number of milliseconds. The difference between this method and the setInterval() method is that it is executed only once.
grammar
setTimeout(code,millisec)
code required. The JavaScript code string to be executed after the function to be called.
millisec Required. The number of milliseconds to wait before executing the code is measured in milliseconds.
hint:
(1) setTimeout() is only executed once. However, if you want to call it multiple times, in addition to using setInterval(), you can also make the executed code call the setTimeout() method again, which has achieved the purpose of multiple executions.
(2) In addition, the setTimeout() method can also return an ID value to facilitate the cancellation of the setTimeout() method using the clearInterval() method.
Example of usage:
The code copy is as follows:
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<script type="text/javascript">
function timedMsg(){
var t=setTimeout("alert('3 seconds time is up!')",3000);
}
function timedMsgAways(){
alert('3 seconds time is up!');
var t=setTimeout("timedMsgAways()",3000);
}
</script>
</head>
<body>
<form>
<input type="button" value="Warning after 3 seconds" onClick="timedMsg()"><br />
<input type="button" value="loop 3 seconds warning" onClick="timedMsgAways()">
</form>
</body>
</html>
For these two methods, it should be noted that if a certain action is required to be executed accurately after a fixed time interval, it is best to use setInterval. If you do not want to interfere with each other due to continuous calls, especially if each function call requires heavy calculations and a long processing time, it is best to use setTimeout.