SetInterval and setTimeout in js use instances

  • 2020-03-30 02:56:40
  • OfStack

SetInterval () definition and usage

The setInterval() method executes a function or expression for a specified period of milliseconds. The method loops through the function until the function is explicitly stopped using clearInterval() or the window is closed. The parameter to the clearInterval() function is the ID value returned by setInterval().

grammar

SetInterval (code, millisec [, "lang"])
Code required. The function to call or the code string to execute.
Millisec must. The interval in milliseconds between the periodic execution or invocation of code.

The return value

A value that can be passed to window.clearinterval () to cancel periodic execution of code.

Examples of use:


<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  The event </button>
</body>
</html>

SetTimeout () definition and usage

The setTimeout() method, which is used to call a function or evaluate an expression after a specified number of milliseconds, differs from the setInterval() method in that it is executed only once.

grammar

SetTimeout (code, millisec)
Code required. The string of JavaScript code to be executed after the function to be called.
Millisec required. The number of milliseconds to wait before executing the code, in milliseconds.

Tip:
(1) setTimeout() although only execute the code once. But if you do, you can also use setInterval() to get the executed code to call the setTimeout() method again for multiple executions.
(2) in addition, setTimeout() method can also return an ID value to facilitate the use of clearInterval() method to cancel the use of setTimeout() method.

Examples of use:


<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<script type="text/javascript">
function timedMsg(){
 var t=setTimeout("alert('3  A second time to !')",3000);
}
function timedMsgAways(){
 alert('3  A second time to !');
 var t=setTimeout("timedMsgAways()",3000);
}
</script>
</head>
<body>
<form>
<input type="button" value="3  Seconds after warning " onClick="timedMsg()"><br />
<input type="button" value=" cycle  3  A second warning " onClick="timedMsgAways()">
</form>
</body>
</html>

For these two methods, it is important to note if required in every once in a fixed time interval after accurately perform an action, so it is best to use the setInterval, and if you don't want to because of their continuous call the problem of mutual interference, especially each function call requires heavy computation and long processing time, so it is best to use setTimeout.


Related articles: