1
0
forked from 0ad/0ad
0ad/binaries/data/mods/public/gui/common/timer.js
Ykkrosh 54d9224918 Add focus() script method to GUI objects.
Add basic GUI script timer.

This was SVN commit r7908.
2010-08-11 21:04:09 +00:00

53 lines
1.1 KiB
JavaScript

var g_TimerID = 0;
var g_Timers = {};
var g_Time = Date.now();
/**
* Set a timeout to call func() after 'delay' msecs.
* Returns an id that can be passed to clearTimeout.
*/
function setTimeout(func, delay)
{
var id = ++g_TimerID;
g_Timers[id] = [g_Time + delay, func];
return id;
}
function clearTimeout(id)
{
delete g_Timers[id];
}
/**
* If you want to use timers, then you must call this function regularly
* (e.g. in a Tick handler)
*/
function updateTimers()
{
g_Time = Date.now();
// Collect the timers that need to run
// (We do this in two stages to avoid deleting from the timer list while
// we're in the middle of iterating through it)
var run = [];
for (var id in g_Timers)
{
if (g_Timers[id][0] <= g_Time)
run.push(id);
}
for each (var id in run)
{
var t = g_Timers[id];
if (!t)
continue; // an earlier timer might have cancelled this one, so skip it
try {
t[1]();
} catch (e) {
var stack = e.stack.trimRight().replace(/^/mg, ' '); // indent the stack trace
error("Error in timer: "+e+"\n"+stack+"\n");
}
delete g_Timers[id];
}
}