The settimeout and setinterval functions that JavaScript uses to handle delay and timed tasks are widely used to handle time-lapse and timed tasks, such as opening a Web page for a period, popping up a login box, sending asynchronous requests to get the latest data at regular intervals, 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 () loops through the function or expression every specified number of milliseconds until clearinterval clears it. That is, settimeout () executes only once, and SetInterval () can execute multiple times. The parameters of the two functions are the same, the first parameter is the code or handle to execute, and the second is the number of milliseconds to delay.
SetTimeout usage
The SetTimeout function uses the following:
var timeoutid = Window.settimeout (func, [Delay, param1, param2, ...]); var
Timeoutid: Timer ID number, which can be used to clear the timer in the Cleartimeout () function.
func: the function being executed.
Code: (Alternative syntax) A string of codes executed.
delay: The delayed time, in milliseconds. If not specified, the default is 0.
We can use Window.settimeout or settimeout, two of them are basically the same, except that Window.settimeout refers to the settimeout function as a property of the global Window object.
Examples of applications:
function Timeout () { document.getElementById (' res '). Innerhtml=math.floor (Math.random () *100 + 1); } SetTimeout ("timeout ()", 5000);
The timeout () function is called after 5 seconds when the code executes.
SetInterval usage
The parameters and usages of the setinterval function are the same as the settimeout function, as described in the usage of the settimeout function above. The difference is that the setinterval executes the Func or code codes at certain intervals.
Examples of applications:
var tt = ten; function Timego () {TT--; document.getElementById ("tt"). InnerHTML =if(tt==0) {window.location.href= '/'; Returnfalse;} } var timer = Window.setinterval ("Timego ()", 1000);
The function Timego () defines the contents of 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 that uses setinterval () to call Timego () every 1 seconds. This timego will be executed 10 times, each time the digital 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);
When the code executes, the page jumps to the homepage after 10 seconds.
Timer usage for JavaScript settimeout () and SetInterval ()