STATIC example
The following is a stopwatch function that returns the number of seconds since the last time it was called.
function stopwatch()
local thisTime, nSecs
thisTime = new Date().getTime()
static lastTime = thisTime
nSecs = (thisTime - lastTime) / 1000
lastTime := thisTime
return nSecs
The function uses a Date object’s getTime( ) method, which keeps time in milliseconds. Whenever the function is called, the variable thisTime is set to the current time in milliseconds. The first time through the function, the lastTime variable is set to that same time. The difference is calculated, and then the value of thisTime is saved in the static variable lastTime for the next function call.
To reset the timer, call the function; you may ignore the return value. Then the next time you call the function, you will get the elapsed time. If you’re measuring a series of intervals, call the function once between intervals. For example:
stopwatch( ) // Reset timer
// Process 1
time1 = stopwatch( ) // Time for first process
// Process 2
time2 = stopwatch( ) // Time for second process
// etc.
The static variable lastTime maintains its value between function calls. The in-line assignment makes sure it has a value the first time the function is called (the function will return zero the first time), and is ignored from then on, unless the variable is explicitly released. The static variable is hidden to all other functions, so you can’t accidentally overwrite it.