Skip to content
This repository was archived by the owner on Feb 26, 2024. It is now read-only.

Commit a8ea55d

Browse files
committed
fix: Allow calling clearTimeout from within the setTimeout callback
Closes #302
1 parent 52073b2 commit a8ea55d

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

lib/browser/browser.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ function patchTimer(
8686
var clearNative = patchMethod(window, cancelName, (delegate: Function) => function(self: any, args: any[]) {
8787
var task: Task = args[0];
8888
if (task && typeof task.type == 'string') {
89-
if (task.cancelFn) {
89+
if (task.cancelFn && task.data.isPeriodic || task.runCount == 0) {
9090
// Do not cancel already canceled functions
9191
task.zone.cancelTask(task);
9292
}

lib/zone.ts

+8
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,11 @@ interface Task {
462462
* at the time of Task creation.
463463
*/
464464
zone: Zone;
465+
466+
/**
467+
* Number of times the task has been executed, or -1 if canceled.
468+
*/
469+
runCount: number;
465470
}
466471

467472
interface MicroTask extends Task {
@@ -565,6 +570,7 @@ var Zone: ZoneType = (function(global) {
565570

566571

567572
runTask(task: Task, applyThis?: any, applyArgs?: any) {
573+
task.runCount++;
568574
if (task.zone != this)
569575
throw new Error('A task can only be run in the zone which created it! (Creation: ' +
570576
task.zone.name + '; Execution: ' + this.name + ')');
@@ -612,6 +618,7 @@ var Zone: ZoneType = (function(global) {
612618

613619
cancelTask(task: Task): any {
614620
var value = this._zoneDelegate.cancelTask(this, task);
621+
task.runCount = -1;
615622
task.cancelFn = null;
616623
return value;
617624
}
@@ -791,6 +798,7 @@ var Zone: ZoneType = (function(global) {
791798
public scheduleFn: (task: Task) => void;
792799
public cancelFn: (task: Task) => void;
793800
public zone: Zone;
801+
public runCount: number = 0;
794802

795803
constructor(type: TaskType, zone: Zone, source: string, callback: Function, options: TaskData,
796804
scheduleFn: (task: Task) => void, cancelFn:(task: Task) => void)

test/browser/setTimeout.spec.ts

+7
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,13 @@ describe('setTimeout', function () {
5252
});
5353
});
5454

55+
it('should allow cancelation of fns while the task is being executed', function (done) {var spy = jasmine.createSpy('spy');
56+
var cancelId = setTimeout(() => {
57+
clearTimeout(cancelId);
58+
done();
59+
}, 0);
60+
});
61+
5562
it('should pass invalid values through', function () {
5663
clearTimeout(null);
5764
clearTimeout(<any>{});

0 commit comments

Comments
 (0)