Files
NativeScript/timer/timer.ios.ts
Hristo Deshev 437e220c42 Zone-aware versions of certain APIs: setTimeout/setInterval mostly.
Instead of waiting for zone.js to patch our global declarations and break
the lazy module loading optimizations there, we'll let it patch stuff
before "globals" gets loaded, so that it doesn't touch (and break) the code
there.

Of course, that requires that functions that need legit patching need to be
made aware of the zone, or get patched later on. The global.zonedCallback
function makes that easy, and we use it for setTimeout/setInterval.
2016-03-31 18:29:42 +03:00

58 lines
1.5 KiB
TypeScript

/**
* iOS specific timer functions implementation.
*/
var timeoutCallbacks = {};
var timerId = 0;
class TimerTargetImpl extends NSObject {
static new(): TimerTargetImpl {
return <TimerTargetImpl>super.new();
}
private _callback: Function;
public initWithCallback(callback: Function): TimerTargetImpl {
this._callback = callback;
return this;
}
public tick(timer): void {
this._callback();
}
public static ObjCExposedMethods = {
"tick": { returns: interop.types.void, params: [NSTimer] }
};
}
function createTimerAndGetId(callback: Function, milliseconds: number, shouldRepeat: boolean): number {
timerId++;
var id = timerId;
var timerTarget = TimerTargetImpl.new().initWithCallback(callback);
var timer = NSTimer.scheduledTimerWithTimeIntervalTargetSelectorUserInfoRepeats(milliseconds / 1000, timerTarget, "tick", null, shouldRepeat);
if (!timeoutCallbacks[id]) {
timeoutCallbacks[id] = timer;
}
return id;
}
export function setTimeout(callback: Function, milliseconds = 0): number {
return createTimerAndGetId(zonedCallback(callback), milliseconds, false);
}
export function clearTimeout(id: number): void {
if (timeoutCallbacks[id]) {
timeoutCallbacks[id].invalidate();
delete timeoutCallbacks[id];
}
}
export function setInterval(callback: Function, milliseconds = 0): number {
return createTimerAndGetId(zonedCallback(callback), milliseconds, true);
}
export var clearInterval = clearTimeout;