2010-08-11 14:04:09 -07:00
|
|
|
var g_TimerID = 0;
|
|
|
|
|
var g_Timers = {};
|
|
|
|
|
var g_Time = Date.now();
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Set a timeout to call func() after 'delay' msecs.
|
2014-01-06 05:32:48 -08:00
|
|
|
* func: function to call
|
|
|
|
|
* delay: delay in ms
|
2010-08-11 14:04:09 -07:00
|
|
|
* 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;
|
|
|
|
|
}
|
|
|
|
|
|
2014-01-06 05:32:48 -08:00
|
|
|
/**
|
|
|
|
|
* deletes a timer
|
|
|
|
|
* id: of the timer
|
|
|
|
|
*/
|
2010-08-11 14:04:09 -07:00
|
|
|
function clearTimeout(id)
|
|
|
|
|
{
|
|
|
|
|
delete g_Timers[id];
|
|
|
|
|
}
|
|
|
|
|
|
2014-01-06 05:32:48 -08:00
|
|
|
/**
|
|
|
|
|
* alters an function call
|
|
|
|
|
* id: of the timer
|
|
|
|
|
* func: function to call
|
|
|
|
|
*/
|
|
|
|
|
function setNewTimerFunction(id, func)
|
|
|
|
|
{
|
2014-01-06 05:48:17 -08:00
|
|
|
if (id in g_Timers)
|
2014-01-06 05:32:48 -08:00
|
|
|
g_Timers[id][1] = func;
|
|
|
|
|
}
|
|
|
|
|
|
2010-08-11 14:04:09 -07:00
|
|
|
/**
|
|
|
|
|
* 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 = [];
|
2025-05-09 07:09:07 -07:00
|
|
|
for (const id in g_Timers)
|
2010-08-11 14:04:09 -07:00
|
|
|
if (g_Timers[id][0] <= g_Time)
|
|
|
|
|
run.push(id);
|
2017-10-21 10:31:05 -07:00
|
|
|
|
2025-05-09 07:09:07 -07:00
|
|
|
for (const id of run)
|
2010-08-11 14:04:09 -07:00
|
|
|
{
|
2025-05-09 07:09:07 -07:00
|
|
|
const t = g_Timers[id];
|
2010-08-11 14:04:09 -07:00
|
|
|
if (!t)
|
|
|
|
|
continue; // an earlier timer might have cancelled this one, so skip it
|
|
|
|
|
|
2025-12-30 00:57:37 -08:00
|
|
|
try
|
|
|
|
|
{
|
2010-08-11 14:04:09 -07:00
|
|
|
t[1]();
|
2025-12-30 00:57:37 -08:00
|
|
|
}
|
|
|
|
|
catch(e)
|
|
|
|
|
{
|
2010-08-11 14:04:09 -07:00
|
|
|
var stack = e.stack.trimRight().replace(/^/mg, ' '); // indent the stack trace
|
2017-10-21 10:31:05 -07:00
|
|
|
error(sprintf("Error in timer: %(error)s", { "error": e }) + "\n" + stack + "\n");
|
2010-08-11 14:04:09 -07:00
|
|
|
}
|
|
|
|
|
delete g_Timers[id];
|
|
|
|
|
}
|
|
|
|
|
}
|