top of page

(Pinardo, 2023)

    An exploration into measuring time in Javascript. Displaying a stopwatch is a common game feature, and we might conceive of two ways to measure the elapsed duration and update it on-screen in Adobe Animate: 1) registering a setInterval() callback or 2) registering an event listener on every 'tick'. Using setInterval() seems promising as we can register a function to be invoked every interval of, say 10 milliseconds, and simply count how many intervals have passed in order to update the stopwatch text. A second approach is to use an event listener for every 'tick'. To determine the elapsed duration, we can use the Date API to keep track of the start time and on every tick, and subtract the current time from the start time to calculate and display the stopwatch value. 

    Lets reimagine this problem. If I were to ask you for a gallon of water, would it be more accurate for you to pour me 16 cups of water, or pour me one, one gallon jug of water? I'd imagine pouring one, one gallon jug of water would be more accurate since pouring 16 consecutive cups of water would accrue some sort of error in the process.

    Similarly, we can hypothesize that the second ticker-based approach is more accurate, as the first approach suffers from inferred cumulative errors accrued over time arising from slight fluctuations in the frequency of the setInterval() callbacks. This contrasts our second approach, which measures absolute time differences/ elapsed time. Further, these errors would garner some sort of increasing numerical difference over time. We can perceive this difference numerically by the experiment file above.

Code for reference:


rootRef = this

var seconds = 0
var initialTime = null 
var timerId = null

createjs.Ticker.addEventListener("tick", onTick)

function onTick(){

    // Using the Date Class with Tick to find the difference in time at click + release
   
   if (initialTime != null)
   {
       var newTime = new Date()
       var differenceInTime = (newTime - initialTime)/1000
       rootRef.text2.text = differenceInTime.toFixed(2)
   }
}

rootRef.car2.addEventListener("mousedown", clickCar)

function clickCar() {
   
   seconds = 0
   initialTime = new Date()
   timeRunning = true
   
   //Set Interval Test
   
   timerId = setInterval(function() {
       if (initialTime != null) {
           seconds += .01
           rootRef.text1.text = seconds.toFixed(2)
       }
   }, 10)


rootRef.car2.addEventListener("pressup", letgoCar) //release on an MC is 'pressup' and not 'mouseup'

function letgoCar(){
   
   clearInterval(timerId)
   // Like event listeners, interval functions also need to be cleared
   // to prevent the timer from running/ being called multiple times at replay

   initialTime = null
   



 

© Patrice Pinardo

bottom of page