May 06, 2021 JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
|
JavaScript executes the code after a set interval We call it a timing event |
By using JavaScript, we have the ability to execute code after a set interval, rather than as soon as a function is called. We call it a timing event.
Using timing events in JavaScritp is easy, and two key methods are:
Note: SetInterval() and setTimeout() are two methods of HTML DOM Window objects.
The setInterval() interval specifies the number of milliseconds and keeps executing the specified code
The window.setInterval() method can use the function setInterval() directly without using the window prefix.
The first argument of setInterval() is a function.
The number of milliseconds between the second arguments
Note: 1000 milliseconds is one second.
Examples show how to use the setInterval() method, but popping up every three seconds is not good for the user experience.
The following example shows the current time. The setInterval() method is set to execute the code every second, just like a watch.
Show the current time
The clearInterval() method is used to stop the function code executed by the setInterval() method.
The window.clearInterval() method can use the function clearInterval() directly without using the window prefix.
To use the clearInterval() method, you must use global variables when creating timing methods:
You can then use the clearInterval() method to stop execution.
For the following example, we added the "Stop time" button:
The setTimeout() method returns a value. I n the statement above, the value is stored in a variable named t. If you want to cancel this setTimeout(), you can use this variable name to specify it.
The first argument to setTimeout() is a string with JavaScript statements. This statement may be such as "alert" or a call to a function, such as "alert Msg()".
The second parameter indicates how many milliseconds from the current one after the first argument is executed.
Tip: 1000 milliseconds equals one second.
The clearTimeout() method is used to stop the function code of the setTimeout() method.
The window.clearTimeout() method can be used without the window prefix.
To use the clearTimeout() method, you must use global variables in the create timeout method (setTimeout):
If the function has not yet been executed, you can use the clearTimeout() method to stop executing the function code.
Here's the same instance, but the "Stop the alert" button has been added: