The following content is excerpted from "Detailed Explanation of Conquering AJAX Web2.0 Development Technology". I read the book in the library today and thought it was very good, so I hereby excerpt it! Small parts of the content and code have been changed!
The window object provides two methods to achieve the timer effect, namely window.setTimeout() and window.setInterval. The former can make a piece of code run after a specified time; while the latter can make a piece of code run once every specified time. Their prototypes are as follows:
window.setTimeout(expression,milliseconds );
window.setInterval(expression,milliseconds);
Among them, expression can be a piece of code enclosed in quotation marks, or it can be a function name. At the specified time, the system will automatically call This function, when using the function name as the calling handle, cannot take any parameters; when using a string, the parameters to be passed can be written in it. The second parameter of the two methods is milliseconds, which represents the number of milliseconds for delay or repeated execution. The two methods are introduced below.
1. window.setTimeout method This method can delay the execution of a function, for example:
]
This code will make the page The dialog "hello" appears after 5 seconds of opening. The last sentence can also be written as:
window.setTimeout("hello()",1000);
Readers can appreciate their differences. This property also exists in the window.setInterval method.
If you want to cancel the delayed execution before the delay period is reached, you can use the window.clearTimeout(timeoutId) method. This method receives an id, which represents a timer. This id is returned by the setTimeout method, for example:
If you need to introduce external Js, you need to refresh to execute
]
In this way, if you want to cancel the display , just click any part of the page, the window.clearTimeout method is executed, so that the timeout operation is cancelled.
2. window.setInterval method
This method causes a function to be called every fixed time and is a very common method. If you want to cancel scheduled execution, similar to the clearTimeout method, you can call the window.clearInterval method. The clearInterval method also receives a value returned by the setInterval method as a parameter. For example:
The code is as follows:
//Define a repeated execution Call
var id=window.setInterval("somefunction",10000);
//Cancel scheduled execution
window.clearInterval(id);
[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]