Home > Article > Web Front-end > Detailed explanation of the use of javascript timer events_Basic knowledge
Using timing events in JavaScript is easy, two key methods are:
setTimeout()
Execute code at some time in the future
clearTimeout()
Cancel setTimeout()
setTimeout()
Syntax
The second parameter indicates how many milliseconds from now the first parameter will be executed.
Tip: 1000 milliseconds equals one second.
When the button in the example below is clicked, a prompt box will pop up after 5 seconds.
Example - Infinite Loop
To create a timer that runs in an infinite loop, we need to write a function that calls itself. In the example below, the input field starts counting from 0 when the button is clicked.
Syntax
Example
The following example is similar to the infinite loop example above. The only difference is that now we've added a "Stop Count!" button to stop the counter:
Syntax:
Example:
Note: In the above example, the execution effect is to alert("hello") every 500ms;
Another clock:
How to stop, setInterval() method??
To be able to use the clearInterval() method, you must use a global variable when creating the interval method:
myVar=setInterval("javascript function",milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.
Example:
stop
}