JavaScript Timing Events
By using JavaScript, we have the ability to execute code after a set interval of time, 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 ()
SetTimeout () syntax
var t=settimeout ("javascript statement", MS)
The SetTimeout () method returns a value. In the above statement, the value is stored in a variable named T. If you want to cancel the setTimeout (), you can use the variable name to specify it.
The first argument to SetTimeout () is a string containing a JavaScript statement. This statement may be such as "alert (' 5 seconds! ')" or a call to a function, such as alertmsg () ".
The second parameter indicates how many milliseconds from the current start to execute the first parameter.
Tip: 1000 milliseconds equals one second.
Instance
When the button in the following example is clicked, a cue box pops up in 5 seconds.
var t=setTimeout("alert(‘5 seconds!‘)",5000)}</script>
Instance-Infinite loopTo create a timer that runs in an infinite loop, we need to write a function to call itself. In the following example, when the button is clicked, the input field is counted starting at 0.
t=setTimeout("timedCount()",1000)}</script>
Cleartimeout () syntaxCleartimeout (settimeout_variable)
InstanceThe following example is similar to the example of an infinite loop above. The only difference is that now we have added a "Stop count!" button to stop this counter:
t=setTimeout("timedCount()",1000)clearTimeout(t)}</script>
JS Timing Event