JavaScript Timing Events
The two methods of using a Window object in a BOM object in JavaScript are the settimeout () method and the Claertimeout () method, which we
Ability to execute code after a set interval, not immediately after the function is called. We call this a timing event.
It is easy to use timing events in JAVASCRITP, and two key methods are:
SetTimeout ()//Future execution of code at some time.
Cleartimeout ()//Cancel settimeout ().
(1) setTimeout () method
Grammar
var time=settimeout ("javascript statement", MS);
The SetTimeout () method returns a value. In the above statement, the value is stored in a variable named time. The first parameter of SetTimeout () is
A string containing the Javascrip statement. This statement may be such as "alert (' 5 seconds! ')" or a call to a function, such as alertmsg () ". Second
A parameter indicates the number of milliseconds from the current to execute the first parameter (hint: 1000 milliseconds equals one second).
(2) Cleartimeout () method
Grammar
Cleartimeout (settimeout_variable);
If you wish to cancel the above settimeout (), you can use the time variable name to specify it. It can be written like this:
Cleartimeout (time);
So let's say a few examples below:
Example one: simple timing
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
The result of the operation is:
Example two: Another simple timing
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
The result of the operation is:
Example three: An infinite loop of timed events
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
Click on the result of the Start Timer button:
Example four: Timing events in an infinite loop with a stop button
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
Click the result of the start timer:
Click the result of the stop timing:
Example five: Clocks made with timed events
This example is actually used in the previous blog post:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
The result of the operation is:
Easy Learning JavaScript 17: JavaScript BOM learning (ii)