SetTimeout (), setInterval (), settimeout
The setTimeout () and setInterval () methods are both JavaScript timing events.
Same
1. Both are two methods of html dom Window object
Can be written
Window. setTimeout ();
Window. setInterval ();
Of course, you can do this without adding a window.
2. Both have two parameters.
SetTimeout ("javascript function", milliseconds );
SetInterval ("javascript function", milliseconds );
The first parameter is a method.
The second parameter is the interval (MS)
Different
1.
SetTimeout (); it is executed only once. After a millisecond value is passed in, the incoming function is executed once. After the execution, the function becomes invalid.
SetInterval (); executes the function cyclically within milliseconds after it is passed in. The (clearInterval () method is used to stop the function code executed by the setInterval () method. )
Instance
After the last three seconds, you can jump to the current page and display the last three seconds on the page.
1. Page
<Body style = "background-color: # EAEAEA; color: # A3A3A3 "> <div> <span id =" totalSecond "> 3 </span> seconds later, the system automatically returns to the home page </div> </body>
2. JS Code
2.1 setTimeout (); Implementation
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 (); Implementation
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 the document. onload event.
Of course, if the two need to call a function, the called function must be prior to the setTimeout and setInterval code.
Because js runs from top to bottom on the page, if it is placed behind setTimeout and setInterval, the function called by it is invalid, and the program will have problems.
As follows:ErrorOf
window.setInterval("interval()", 1000); function interval() {var total = totalSecond.innerText; if(total <= 0) {location.href = "http://www.baidu.com";} else {totalSecond.innerText = --total;}}
There is also a three-second page Jump method, add the following code in the head tag, of course, page seconds display also need to add yourself
<Meta http-equiv = "Refresh" content = "3; url = http://www.baidu.com.cn"/>