The usage of SetInterval and setTimeout in JavaScript is explained in detail

  • 2020-10-23 20:02:10
  • OfStack

setTimeout

describe

setTimeout(code,millisec)

The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds.

Note: During the call, you can terminate using clearTimeout(id_of_settimeout)

参数 描述
code 必需,要调用的函数后要执行的 JavaScript 代码串。
millisec 必需,在执行代码前需等待的毫秒数。

setTimeinterval

setInterval(code,millisec[,"lang"])

参数 描述
code 必需,要调用的函数或要执行的代码串。
millisec 必需,周期性执行或调用code之间的时间间隔,以毫秒计。

The setInterval() method can call a function or evaluate an expression for a specified period in milliseconds.

Set the delay time in JS:

Using SetInterval is similar to setting the delay function setTimeout. setTimeout is used to delay an operation for a period of time.

setTimeout("function",time) sets 1 timeout object setInterval("function",time) sets 1 timeout object

SetInterval is automatic repetition, setTimeout does not repeat.

clearTimeout(Object) Clears set setTimeout (object) Clears set setInterval (object)

The setInterval() method can call a function or evaluate an expression for a specified period in milliseconds.

The window object provides two methods to achieve the effect of the timer: window.setTimeout () and window.setInterval. The former can make 1 piece of code run after a specified time; The latter can cause a piece of code to run once every specified time. Their prototypes are as follows: window.setTimeout(expression,milliseconds); window.setInterval(expression,milliseconds); expression can be either a piece of code enclosed in quotation marks or a function name. At the specified time, the system will automatically call this function. When the function name is used as the call handle, no arguments can be taken. With a string, you can write the argument you want to pass. The second argument to both methods is milliseconds, which represents the number of milliseconds of delay or repeated execution.

The two methods are described below.

1. window. setTimeout method this method can delay the execution of 1 function, for example:


<script language="JavaScript" type="text/javascript">
<!--
 function hello(){ alert("hello"); } window.setTimeout(hello,5000);
//-->
 </script>

This code will cause the dialog "hello" to appear five seconds after the page has opened. The last sentence can also be written: window.setTimeout("hello()",5000); The reader can appreciate the difference, and this property is also present in the ES95en.setInterval method. If the delay is cancelled before the delay deadline is reached, you can use the window.clearTimeout (timeoutId) method, which receives 1 id, representing 1 timer. This id is returned by the setTimeout method, for example:


<script language="JavaScript" type="text/javascript">
<!--
function hello(){   
alert("hello");
}
var id=window.setTimeout(hello,5000);
document.onclick=function(){   
window.clearTimeout(id);
 }
//-->
</script>

This way, if you want to undisplay, you just click any 1 part of the page and the window.clearTimeout method is executed, making the timeout cancelled.

2. window.setInterval This method makes a function call every fixed time, is a very common method. If you want to cancel scheduled execution, similar to the clearTimeout method, you can call the ES113en.clearInterval method. The clearInterval method also receives the value returned by 1 setInterval method as a parameter. For example: // define a repeated call var id= window.setInterval ("somefunction",10000); // Cancel window. clearInterval(id); The above code is only used to show how to cancel 1 timed execution. The setInterval method is actually used in a number of situations, and the purpose of the setInterval function is described by designing a stopwatch: the stopwatch will consist of two buttons and a text box to display the time. The timer starts when the start button is clicked with a minimum of 0.01 seconds, and stops when the button is clicked again, with the text box showing the elapsed time. Another button is used to reset the current time to zero. Its implementation code is as follows:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
<head>
 <title> New Document </title>
 </head> 
<body> 
<form action="somepage.asp"> 
<input type="text" value="0" name="txt1"/> 
<input type="button" value=" start " name="btnStart"/> 
<input type="button" value=" reset " name="btnReset"/> 
</form> 
</body> 
</html>

<script language="JavaScript" type="text/javascript">
<!--
// Gets the form fields in the form 
var txt=document.forms[0].elements["txt1"];
 var btnStart=document.forms[0].elements["btnStart"];
 var btnReset=document.forms[0].elements["btnReset"]
 // Define the timer id
var id;
// every 10 The millisecond value increases 1
var seed=0;
btnStart.onclick=function(){   
// Determine the current operation based on the button text    
 if(this.value==" start "){       
 // Causes the button text to stop        
 this.value=" stop ";       
// Makes the reset button unavailable        
 btnReset.disabled=true;       
// Set the timer for each 0.01s jump 1 time        
id=window.setInterval(tip,10);    }
else{       
// Causes the button text to start        
this.value=" start ";       
// Makes the reset button available        
 btnReset.disabled=false;       
// Cancel the timing        
window.clearInterval(id);   
 } }
// The reset button 
btnReset.onclick=function(){   
seed=0;
 }
// Let a stopwatch to jump 1 " 
 function tip(){  
  seed++;   
 txt.value=seed/100;
}
//-->
</script>

Passing arguments to timer calls, whether window.setTimeout or window.setInterval, does not take arguments when using the function name as a call handle, which in many cases must be done, and needs to be resolved in some way. For example, for the function hello(_name), it is used to display the welcome message for the user name: var userName="jack";


// Display welcome information based on the user name 
function hello(_name){   
 alert("hello,"+_name);
 }

At this point, it is not feasible to attempt to delay the execution of the hello function by 3 seconds by using the following statement:

window.setTimeout(hello(userName),3000);

This causes the hello function to execute immediately and passes the return value as a call handle to the setTimeout function, the result of which is not what the program needs. The desired result can be achieved by using the string form:

window.setTimeout("hello(userName)",3000);

The string here is 1 piece of JavaScript code, where userName represents the variable. But this is not intuitive, and in some cases the function name must be used. Here is a trick to implement a function call with arguments:


<script language="JavaScript" type="text/javascript"> <!-- var userName="jack";
// Display welcome information based on the user name 
function hello(_name){    
alert("hello,"+_name);
}
// create 1 A function that returns 1 A parameterless function 
function _hello(_name){    
return function(){       
hello(_name);    } }
window.setTimeout(_hello(userName),3000);
 //-->
</script>

Here you define a function _hello that takes 1 argument and returns a function with no arguments, using the arguments of an external function inside the function, and therefore calling it without arguments. In the ES161en. setTimeout function, _hello(userName) is used to return a function handle with no arguments, thus achieving parameter passing.

There are two main timing methods for window objects, setTimeout and setInteval. The syntax of setTimeout and setInteval are basically the same, but they perform different functions.

The setTimeout method is a timer, that is, what to do after what time. When you're done, pull it down.

The setInterval method represents the repeated execution of an operation at a fixed interval of 1.

Set delay time in JS:

Using SetInterval is similar to setting the delay function setTimeout. setTimeout is used to delay an operation for a period of time.

setTimeout("function",time) sets 1 timeout object

setInterval("function",time) sets 1 timeout object

SetInterval is automatically repeated. setTimeout does not repeat.

clearTimeout(object) clears the setTimeout object that has been set

clearInterval(object) clears the setInterval object that has been set

If you use setTimeout to realize the functions of setInerval, you need to periodically call yourself in the executing program. If the counter needs to be cleaned, different methods are called according to the method used:

Such as:


tttt=setTimeout('northsnow()',1000);
clearTimeout(tttt);

Or:


tttt=setInterval('northsnow()',1000);
clearInteval(tttt);

Here's an example:


<div id="liujincai">
</div>
<input type="button" name="start" value="start" onclick='startShow();'>
<input type="button" name="stop" value="stop" onclick="stop();">
<script language="javascript">  
var intvalue=1;  
var timer2=null;  
function startShow()  {   
 liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();   
timer2=window.setTimeout("startShow()",2000);  }  
function stop()  {   
 window.clearTimeout(timer2);  
 }
</script>

Or:


<div id="liujincai">
</div>
<input type="button" name="start" value="start" onclick='timer2=window.setInterval("startShow()",2000);//startShow();'>
<input type="button" name="stop" value="stop" onclick="stop();">
<script language="javascript">  
 var intvalue=1;  
var timer2=null;  
 function startShow()  {   
 liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();  
 }  
 function stop()  {   
 window.clearInterval(timer2);  
}
</script>

The above is a detailed explanation of the usage of SetInterval and setTimeout in JavaScript. I hope it will be helpful for you to learn the knowledge of SetInterval and setTimeout.


Related articles: