JS can achieve a lot of Java code is not easy to complete the function. Here to learn some of the timer events in JS.
JavaScript executes code after a set interval of time, called a timing event.
Mainly through two methods to achieve:
1.setInterval ()-interval specifies the number of milliseconds to execute the specified code continuously.
2.setTimeout ()-executes the specified code after pausing the specified number of milliseconds
Also, both methods are methods of the Window object.
First, the SetInterval () method is introduced, and the method is worth the interval of a certain number of milliseconds to execute the specified code.
Syntax: Window.setinterval ("JS code, functions, etc.", milliseconds);
Example 1: A Hello is popped every three seconds
SetInterval (function () {alert ("Hello")},3000);
Example 2: Display the current time, through the button to achieve the stop of time, start
<script type= "Text/javascript" >varMyVar; functionStarttimer () {/*setinterval () interval specifies the number of milliseconds to execute the specified code repeatedly*/MyVar=setinterval (function() {MyTimer ()},1000); } functionMyTimer ()/*define a function that gets local time*/ { varD=NewDate (); vart=d.tolocaletimestring (); document.getElementById ("Demo"). innerhtml=T; } functionStoptimer () {/*clearinterval () method to stop the function code executed by the SetInterval () method*/clearinterval (MyVar); } </script>settimeout () method
In HTML or JSP
<Body> <h4ID= "Demo"></h4> <inputtype= "button"onclick= "Starttimer ()"value= "Start"> <inputtype= "button"onclick= "Stoptimer ()"value= "Stop"></Body>
For the settimeout () method, the specified code or method is executed after the specified number of milliseconds.
Syntax: Window.settimeout ("javascript function ", number of milliseconds );
Example 1:3 seconds after the "Hello" prompt box pops up
SetTimeout (function () {alert ("Hello")},3000);
Example 2: Three seconds to jump to previous page
<script type= "Text/javascript" > setTimeout (function() { Window.history.back ( ); },(); </script>
How do I stop it?
The Cleartimeout () method is used to stop executing the function code of the SetTimeout () method. Note here that MyVar must be a global variable. Examples are as follows:
var MyVar; function myFunction () { MyVar=settimeout (function() {alert ("Hello")},3000); } function mystopfunction () { cleartimeout (myVar); }
The above will be the basic function of the JS timer briefly introduced, the specific use of the scene, want to understand deeply, only to the project to use the time before you can have a new disregard.
Timer events in JS