Skip to content

Commit

Permalink
fix(snack-bar): handle large numbers passed in as duration (#17239)
Browse files Browse the repository at this point in the history
Handles very large numbers being passed in as a snack bar duration (e.g. `Infinity`). We need to cap the duration, otherwise the browser will revert it back to 1 if it's too large.

Fixes #17234.
  • Loading branch information
crisbeto authored and mmalerba committed Oct 18, 2019
1 parent 3476f51 commit 86a8fee
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/material/snack-bar/snack-bar-ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export interface MatSnackBarDismiss {
dismissedByAction: boolean;
}

/** Maximum amount of milliseconds that can be passed into setTimeout. */
const MAX_TIMEOUT = Math.pow(2, 31) - 1;

/**
* Reference to a snack bar dispatched from the snack bar service.
*/
Expand Down Expand Up @@ -85,7 +88,9 @@ export class MatSnackBarRef<T> {

/** Dismisses the snack bar after some duration */
_dismissAfter(duration: number): void {
this._durationTimeoutId = setTimeout(() => this.dismiss(), duration);
// Note that we need to cap the duration to the maximum value for setTimeout, because
// it'll revert to 1 if somebody passes in something greater (e.g. `Infinity`). See #17234.
this._durationTimeoutId = setTimeout(() => this.dismiss(), Math.min(duration, MAX_TIMEOUT));
}

/** Marks the snackbar as opened */
Expand Down
13 changes: 13 additions & 0 deletions src/material/snack-bar/snack-bar.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,19 @@ describe('MatSnackBar', () => {
expect(overlayContainerElement.childElementCount).toBe(0);
}));

it('should cap the timeout to the maximum accepted delay in setTimeout', fakeAsync(() => {
const config = new MatSnackBarConfig();
config.duration = Infinity;
snackBar.open('content', 'test', config);
viewContainerFixture.detectChanges();
spyOn(window, 'setTimeout').and.callThrough();
tick(100);

expect(window.setTimeout).toHaveBeenCalledWith(jasmine.any(Function), Math.pow(2, 31) - 1);

flush();
}));

describe('with custom component', () => {
it('should open a custom component', () => {
const snackBarRef = snackBar.openFromComponent(BurritosNotification);
Expand Down

0 comments on commit 86a8fee

Please sign in to comment.