The Window.setinterval () method and the Window.settimeout () method are used by the timer in JS,
where the SetInterval () method performs a method at intervals, and Window.settimeout () invokes the function for a period of time.
The SetTimeout () method typically implements a timer by invoking its own iteration. Corresponding to these two methods, there is also the effect of clearing these two functions
Two methods, respectively, are Window.clearinterval () and Window.cleartimeout ().
1.setInterval () and Clearinterval () (window can be omitted)
(1) The common syntax for the SetInterval () method is as follows:
SetInterval (Function,interval);
where function is the functions that will be executed within the interval, interval is the interval of time, in milliseconds.
(2) The common syntax for the Clearinterval () method is as follows:
Timer = setinterval (function,interval);
Clearinterval (timer);
Example:
123<body>4<p id= "Timer" > Click to start Timing! </p>5<div>6<button id= "Cuttimer" onclick= "Start ()" > Start </button>7<button id= "Cuttimer" onclick= "Stop ()" > Stop </button>8</div>9<script>Ten varCutt = document.getElementById ("Cuttimer"); One A varTimer1 =NULL; - - functionstart () { the varCounttime =function(){ -Date =NewDate (); -Datestr =date.tolocaletimestring (); -document.getElementById ("Timer"). InnerHTML =Datestr; + } - +Timer1 = Window.setinterval (counttime,1000); A at } - - - functionStop () { -Console.log ("Timer stop:" +timer1); - Window.clearinterval (timer1); in }; - to</script> +</body> -In this example, after clicking Start (there will be a delay), the page executes every 1000 milliseconds (that is, 1 seconds), that is, the current time division seconds.
2.setTimeout () and cleartimeout ()
These two methods are similar to the setinterval () and Clearinterval () method usages, as shown in the following example:
123<body>4<p id= "Timer" ></p>5<div>6<button id= "Cuttimer" onclick= "Timeoutalert ();" > Execution </button>7<button id= "Cuttimer" onclick= "Stoptimeoutalert ();" > Stop </button>8</div>9<script>TenTimeOut =NULL; One functionTimeoutalert () { ATimeOut = Window.settimeout (function(){ -Console.log ("Time out ..." +timeOut); - Timeoutalert (); the},1000); - } - - functionStoptimeoutalert () { +Console.log ("Timecut:" +timeOut); - window.cleartimeout (timeOut); + } A</script> at</body> -You can see that the Timeoutalert () method calls itself every 1000 milliseconds, prints the value of the current timeout in the console, and the timeout is used for the first time.
After SetTimeout () is 1, each increment of 1,cleartimeout () clears the current setTimeout () by this number as the entry parameter.
The use of JS timer method