JavaScript's settimeout and setinterval functions are widely used to deal with delays and timed tasks, such as opening a Web page for a period of time after a pop-up login box, the page to send asynchronous requests every time to obtain the latest data and so on. But there are differences in their application.
The settimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds, while SetInterval () invokes the function or expression at the specified number of milliseconds, until clearinterval clears it. That is, settimeout () is executed only once, and setinterval () can be executed multiple times. The parameters for two functions are the same, the first is the code or handle to execute, and the second is the number of milliseconds to delay.
SetTimeout usage
The use of the SetTimeout function is as follows:
var Timeoutid = Window.settimeout (func, [Delay, param1, param2, ...]);
var timeoutid = window.settimeout (code, [delay]);
Timeoutid: The timer ID number, which can be used to clear the timer in the Cleartimeout () function.
Func: The function that is executed.
Code: (alternative syntax) a coded string to be executed.
Delay: Delay time, in units of milliseconds. If not specified, the default is 0.
We can use Window.settimeout or settimeout, two of them are basically the same, except that the SetTimeout function is referenced as a property of the global Window object.
application Example:
function timeout () {
document.getElementById (' res '). Innerhtml=math.floor (Math.random () *100 + 1);
}
settimeout ("timeout ()", 5000);
When code executes, call the timeout () function after 5 seconds, and click on the demo.
SetInterval usage
The parameters and usages of the setinterval function are the same as the settimeout function, please refer to the use of the settimeout function above. The difference is that setinterval executes the Func or code codes at every interval.
application Example:
var tt = 10;
function Timego () {
tt--;
document.getElementById ("tt"). InnerHTML = TT;
if (tt==0) {
window.location.href= '/';
return false;
}
}
var timer = Window.setinterval ("Timego ()", 1000);
The function Timego () defines the content that the page element #tt display, and when TT equals 0 o'clock, the page is directed to the homepage. Then we define a timer timer and use SetInterval () to call Timego () every 1 seconds. This timego will be performed 10 times, each time the number TT will be reduced by 1 until 0. So if you want to stop the timer, you can use the following code:
Window.clearinterval (timer);
Code execution, 10 seconds after the page jump to the homepage, click to see the demo.
In fact, settimeout () can also implement a function every once in a while, but we still make a simple difference between using settimeout and setinterval. In addition, JavaScript is running in a single-threaded way in the browser's JavaScript engine, the actual application of complex tasks in the need to queue execution, which may lead to timer time is not allowed, this problem in large applications need to consider, this article does not delve into.
The difference between settimeout and setinterval
SetInterval after executing the code once, after the fixed time interval, it will also automatically repeat the execution of the Code
SetTimeout only executes the code one time.
Although it appears that settimeout can only be applied to on-off actions, you can repeat the call to settimeout by creating a function loop:
File:settimeout_setinterval.js
ShowTime ();
function ShowTime ()
{
var today = new Date ();
Alert ("The time is:" + today.tostring ());
SetTimeout ("ShowTime ()", 5000);
}
Once this function is called, the time is displayed every 5 seconds. If you use SetInterval, the corresponding code looks like this:
File:settimeout_setinterval2.js
SetInterval ("ShowTime ()", 5000);
function ShowTime ()
{
var today = new Date ();
Alert ("The time is:" + today.tostring ());
}
The two methods may look very much alike, and the results will be similar, but the big difference is that the SetTimeout method does not perform a showtime function every 5 seconds, and it executes the Showtime function 5 seconds after each call to settimeout. This means that if the body part of the Showtime function takes 2 seconds to complete, the entire function is executed once every 7 seconds. But setinterval is not bound by the function it calls, it simply repeats the function once at a certain time.
If it is required to perform an action precisely after every fixed interval of time, it is best to use setinterval, and if you do not want to cause interference problems due to successive calls, especially if the call to each function requires heavy computation and lengthy processing time, it is best to use settimeout.
Use of function pointers
The first parameter in the two timer function is a string of code, but the parameter can also be a function pointer, but IE 5 under Mac does not support this.
If you use function pointers as the second argument of the settimeout and setinterval functions, then they can perform a function defined elsewhere:
SetTimeout (ShowTime, 500);
function ShowTime ()
{
var today = new Date ();
Alert ("The time is:" + today.tostring ());
}
Alternatively, an anonymous function can be declared as an inline function:
settimeout (function () {var today = new Date ();
Alert ("The time is:" + today.tostring ());}, 500);
Discussion
If the timer function is not processed, then SetInterval will continue to execute the same code until the browser window closes, or the user moves to another page. However, there are ways to terminate the execution of the settimeout and setinterval functions.
When the setinterval call completes, it returns a timer ID that can be accessed by the timer in the future and, if passed to Clearinterval, terminates the execution of the invoked process code, as follows:
File:settimeout_setinterval3.js (excerpt)
var intervalprocess = setinterval ("alert (' goal! ')", 3000);
var stopgoallink = document.getElementById ("Stopgoallink");
Attacheventlistener (Stopgoallink, "click", Stopgoal, false);
function Stopgoal ()
{
Clearinterval (intervalprocess);
}
As long as click on the Stopgoallink, no matter when the click, Intervalprocess will be canceled, will not continue to carry out repeated intervalprocess. If SetTimeout is canceled within the timeout period, this termination effect can also be implemented on SetTimeout, as follows:
File:settimeout_setinterval4.js (excerpt)
var timeoutprocess = settimeout ("alert (' goal! ')", 3000);
var stopgoallink = document.getElementById ("Stopgoallink");
Attacheventlistener (Stopgoallink, "click", Stopgoal, false);
function Stopgoal ()
{
Cleartimeout (timeoutprocess);
}
Take a look at two more examples
Example, SetInterval
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<meta name= "generator" content= "EditPlus" >
<meta name= "Author" content= "" >
<meta name= "Keywords" content= "" >
<meta name= "Description" content= "" >
</HEAD>
<BODY>
<div id= "Time" ></div>
<script language= "JavaScript" >
<!--
var Timeid;
function SetTime () {
var date=new date ();
var h=date.gethours ();
var m=date.getminutes ();
var s=date.getseconds ();
document.getElementById ("Time"). innerhtml=h+ ":" +m+ ":" +s;
}
Timeid=setinterval ("SetTime ()", 1000);//His call is called externally, not recursively, representing every 1s call
function Stop () {
Clearinterval (Timeid);
}
-->
</SCRIPT>
<input type= "button" value= "Pause" onclick= "Stop ()" >
<input type= "button" value= "Start" onclick= "Timeid=setinterval (' settime () ', 1000);" >
</BODY>
</HTML>
Example 2, settimeout
[XHTML] View plaincopy
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<meta name= "generator" content= "EditPlus" >
<meta name= "Author" content= "" >
<meta name= "Keywords" content= "" >
<meta name= "Description" content= "" >
</HEAD>
<BODY>
<div id= "Time" ></div>
<script language= "JavaScript" >
<!--
var Timeid;
function SetTime () {
var date=new date ();
var h=date.gethours ();
var m=date.getminutes ();
var s=date.getseconds ();
document.getElementById ("Time"). innerhtml=h+ ":" +m+ ":" +s;
Timeid=settimeout ("SetTime ()", 1000);//Recursive call, representing the execution once after 1s
}
SetTime ()//page load start execution
function Stop () {
Cleartimeout (Timeid);
}
-->
</SCRIPT>
<input type= "button" value= "Pause" onclick= "Stop ()" >
<input type= "button" value= "Start" onclick= "Timeid=setinterval (' settime () ', 1000);" >
</BODY>
</HTML>