SetTimeout () and SetInterval () Two methods are all JavaScript timed events
same
1. Two of the two methods for HTML DOM window objects
Use can be written as
Window.settimeout ();
Window.setinterval ();
Of course it's OK not to add Windows.
2. Both have two parameters
The code is as follows |
Copy Code |
SetTimeout ("JavaScript function", milliseconds);
SetInterval ("JavaScript function", milliseconds); |
The first parameter is a method
The second parameter is a time interval (milliseconds)
different
1.setTimeout (); Pass in a millisecond number of times to execute an incoming function function once it arrives, and the function fails after execution.
setinterval (); loop execution, loop through the incoming function function during the incoming millisecond interval, and do not fail after execution. (Clearinterval () method to stop the function code that the SetInterval () method executes. The
Instance
implements the countdown of three seconds before jumping to the current page and displaying the countdown on the page.
1. Page
The code is as follows |
Copy Code |
<body style= "Background-color: #EAEAEA; Color: #A3A3A3 "> <div> <span id= "Totalsecond" Automatically returns to home page after >3</span> seconds </div> </body> |
2.JS Code
2.1 settimeout ();
code is as follows |
copy code |
function Timeout () { var total = totalsecond.innertext; if ( Total <= 0) { location.href = "http://www.baidu.com"; } else { totalsecond.innertext =--total; window.settimeout ("timeout ()", 1000); } } Window.settimeout ("timeout ()", 1000); |
2.2 SetInterval ();
The code is as follows |
Copy Code |
function interval () { var total = Totalsecond.innertext; if (total <= 0) { Location.href = "http://www.baidu.com"; } else { Totalsecond.innertext =--total; } } Window.setinterval ("Interval ()", 1000); |
Note:
settimeout and setinterval are automatically executed after the page is loaded. Therefore, you do not need to add document.onload events.
Of course, if both need to invoke function then the function called must precede the settimeout and SetInterval code.
Because JS runs from top to bottom on the page, if the function called after settimeout and setinterval is not a valid method, the program will go wrong.
is the wrong
code is as follows |
copy code |
window.setinterval ("Interval ()", 1000); function interval () { var total = Totalsecond.innert ext; if (total <= 0) { Location.href = "http://www.baidu.com"; } else { totalsecond.innertext =--total; } } |
also has a three seconds after the page jump method, add the following code in the head tag, of course, the page seconds display also need to add their own
<meta http-equiv= "Refresh" content= "3; url=http:// www.baidu.com.cn "/>