Document directory
- Syntax
- Instance
- Instance-Infinite Loop
- Syntax
- Instance
By using JavaScript, we have the ability to execute code after a set interval, rather than immediately after the function is called. We call it a timing event.
Instance
-
Simple timing
-
After you click the button in this example, a warning box will pop up in five seconds.
-
Another simple timing
-
In this example, the program runs 2 seconds, 4 seconds, and 6 seconds.
-
Timing events in an infinite loop
-
In this example, after you click the start timer button, the program starts to time in seconds from 0.
-
Timing events in an infinite loop with a stop button
-
In this example, click the Count button and start the countdown based on the value entered by the user. Click the stop button to stop the timer.
-
Clocks and clocks created using timing events
-
A small JavaScript clock
Javascript timing event
By using JavaScript, we have the ability to execute code after a set interval, rather than immediately after the function is called. We call it a timing event.
It is easy to use timing events in javascrui. The two key methods are as follows:
-
SetTimeout ()
-
Execute Code at a certain time in the future
-
Cleartimeout ()
-
Cancel setTimeout ()
SetTimeout () syntax
VaR T = setTimeout ("javascript statement", millisecond)
The setTimeout () method returns a value. In the preceding statement, the value is stored in the variable t. If you want to cancel this setTimeout (), you can use this variable name to specify it.
The first parameter of setTimeout () is a string containing JavaScript statements. This statement may be like "alert ('5 seconds! ') ", Or call a function, such as alertmsg ()".
The second parameter indicates how many milliseconds since the current time the first parameter will be executed.
Tip: 1000 milliseconds equals one second.
Instance
When the button in the following example is clicked, a prompt box will pop up in five seconds.
var t=setTimeout("alert('5 seconds!')",5000) }</script>Instance-Infinite Loop
To create a timer running in an infinite loop, We need to compile a function to call itself. In the following example, when the button is clicked, the input field starts counting from 0.
t=setTimeout("timedCount()",1000) }</script>Cleartimeout () syntax
clearTimeout(setTimeout_variable)
Instance
The following example is similar to the above infinite loop example. The only difference is that now we have added a "stop count! "Button to stop this counter:
t=setTimeout("timedCount()",1000) }function stopCount() { clearTimeout(t)
}</script>