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

Commit

Permalink
fix: Allow calling clearTimeout from within the setTimeout callback
Browse files Browse the repository at this point in the history
Closes #302
  • Loading branch information
mhevery committed Mar 28, 2016
1 parent 52073b2 commit a8ea55d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/browser/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ function patchTimer(
var clearNative = patchMethod(window, cancelName, (delegate: Function) => function(self: any, args: any[]) {
var task: Task = args[0];
if (task && typeof task.type == 'string') {
if (task.cancelFn) {
if (task.cancelFn && task.data.isPeriodic || task.runCount == 0) {
// Do not cancel already canceled functions
task.zone.cancelTask(task);
}
Expand Down
8 changes: 8 additions & 0 deletions lib/zone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,11 @@ interface Task {
* at the time of Task creation.
*/
zone: Zone;

/**
* Number of times the task has been executed, or -1 if canceled.
*/
runCount: number;
}

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


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

cancelTask(task: Task): any {
var value = this._zoneDelegate.cancelTask(this, task);
task.runCount = -1;
task.cancelFn = null;
return value;
}
Expand Down Expand Up @@ -791,6 +798,7 @@ var Zone: ZoneType = (function(global) {
public scheduleFn: (task: Task) => void;
public cancelFn: (task: Task) => void;
public zone: Zone;
public runCount: number = 0;

constructor(type: TaskType, zone: Zone, source: string, callback: Function, options: TaskData,
scheduleFn: (task: Task) => void, cancelFn:(task: Task) => void)
Expand Down
7 changes: 7 additions & 0 deletions test/browser/setTimeout.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ describe('setTimeout', function () {
});
});

it('should allow cancelation of fns while the task is being executed', function (done) {var spy = jasmine.createSpy('spy');
var cancelId = setTimeout(() => {
clearTimeout(cancelId);
done();
}, 0);
});

it('should pass invalid values through', function () {
clearTimeout(null);
clearTimeout(<any>{});
Expand Down

0 comments on commit a8ea55d

Please sign in to comment.