Skip to content

Commit 146160c

Browse files
Sven Reglitzkijelbourn
authored andcommitted
fix(snackbar): clear timeout upon dismiss (#4860)
1 parent 06070ae commit 146160c

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

src/lib/snack-bar/snack-bar-ref.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@ export class MdSnackBarRef<T> {
3939
/** Subject for notifying the user that the snack bar action was called. */
4040
private _onAction: Subject<any> = new Subject();
4141

42+
/**
43+
* Timeout ID for the duration setTimeout call. Used to clear the timeout if the snackbar is
44+
* dismissed before the duration passes.
45+
*/
46+
private _durationTimeoutId: number;
47+
4248
constructor(instance: T,
4349
containerInstance: MdSnackBarContainer,
4450
private _overlayRef: OverlayRef) {
@@ -55,6 +61,12 @@ export class MdSnackBarRef<T> {
5561
if (!this._afterClosed.closed) {
5662
this.containerInstance.exit();
5763
}
64+
clearTimeout(this._durationTimeoutId);
65+
}
66+
67+
/** Dismisses the snack bar after some duration */
68+
_dismissAfter(duration: number): void {
69+
this._durationTimeoutId = setTimeout(() => this.dismiss(), duration);
5870
}
5971

6072
/** Marks the snackbar action clicked. */

src/lib/snack-bar/snack-bar.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,20 @@ describe('MdSnackBar', () => {
328328
expect(dismissObservableCompleted).toBeTruthy('Expected the snack bar to be dismissed');
329329
}));
330330

331+
it('should clear the dismiss timeout when dismissed before timeout expiration', fakeAsync(() => {
332+
let config = new MdSnackBarConfig();
333+
config.duration = 1000;
334+
snackBar.open('content', 'test', config);
335+
336+
setTimeout(() => snackBar.dismiss(), 500);
337+
338+
tick(600);
339+
viewContainerFixture.detectChanges();
340+
flushMicrotasks();
341+
342+
expect(viewContainerFixture.isStable()).toBe(true);
343+
}));
344+
331345
it('should add extra classes to the container', () => {
332346
snackBar.open(simpleMessage, simpleActionLabel, { extraClasses: ['one', 'two'] });
333347
viewContainerFixture.detectChanges();

src/lib/snack-bar/snack-bar.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ export class MdSnackBar {
8989
// If a dismiss timeout is provided, set up dismiss based on after the snackbar is opened.
9090
if (config.duration && config.duration > 0) {
9191
snackBarRef.afterOpened().subscribe(() => {
92-
setTimeout(() => snackBarRef.dismiss(), config!.duration);
92+
snackBarRef._dismissAfter(config!.duration!);
9393
});
9494
}
9595

0 commit comments

Comments
 (0)