Implementing a javascript timer is useful for a number of reasons. For example, we could build an action that pops up a new image every 4 seconds, or create a clock that counts down to a certain time. It has many uses. The javascript timer below uses setInterval to trigger a function every 6 seconds.
It’s important to note that setInterval is defined as:
A method that calls a function or evaluates an expression at specified intervals (in milliseconds).
It continues to call this interval until clearInterval() is used.
Notice that it uses milliseconds as opposed to normal seconds. This gives us a lot more flexibility as we can utilize half second intervals if need be. In the case below, I convert seconds to milliseconds by multiplying it by 1000.
| Javascript | | copy code | | ? |
| 01 | |
| 02 | //define variables, and convert to milliseconds for usage with setInterval() |
| 03 | var int; |
| 04 | var seconds = 6; |
| 05 | var millisecs = seconds*1000; |
| 06 | |
| 07 | //Start the function containing the timer |
| 08 | StartTimer(); |
| 09 | |
| 10 | function StartTimer(){ |
| 11 | //use the setInterval() function |
| 12 | int=self.setInterval(myFunction, millisecs); |
| 13 | } |
| 14 | |
| 15 | function ResetTimer(){ |
| 16 | //Clear the interval for the timer. |
| 17 | window.clearInterval(int); |
| 18 | } |
| 19 | //Write a function that does something when the setInterval is fired. |
| 20 | myFunction(){ |
| 21 | alert("This will fire every "+seconds+" seconds") |
| 22 | } |


No comments yet