Skip to content

fix(snack-bar): handle large numbers passed in as duration #17239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why doesn't Number.MAX_SAFE_INTEGER work for this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK MAX_SAFE_INTEGER is 64bit, whereas setTimeout accepts 32bit.


/**
* 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