Skip to content

Commit f6348f6

Browse files
Clear timeout before showing the toast (#31155)
* clear timeout before showing the toast * Add unit test * Remove the check for timeout * Check for clearTimeout to have been called Co-authored-by: XhmikosR <[email protected]>
1 parent 6acdfdb commit f6348f6

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

js/src/toast.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ class Toast {
9191
return
9292
}
9393

94+
this._clearTimeout()
95+
9496
if (this._config.animation) {
9597
this._element.classList.add(CLASS_NAME_FADE)
9698
}
@@ -149,8 +151,7 @@ class Toast {
149151
}
150152

151153
dispose() {
152-
clearTimeout(this._timeout)
153-
this._timeout = null
154+
this._clearTimeout()
154155

155156
if (this._element.classList.contains(CLASS_NAME_SHOW)) {
156157
this._element.classList.remove(CLASS_NAME_SHOW)
@@ -186,6 +187,11 @@ class Toast {
186187
)
187188
}
188189

190+
_clearTimeout() {
191+
clearTimeout(this._timeout)
192+
this._timeout = null
193+
}
194+
189195
// Static
190196

191197
static jQueryInterface(config) {

js/tests/unit/toast.spec.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,33 @@ describe('Toast', () => {
170170

171171
toast.show()
172172
})
173+
174+
it('should clear timeout if toast is shown again before it is hidden', done => {
175+
fixtureEl.innerHTML = [
176+
'<div class="toast">',
177+
' <div class="toast-body">',
178+
' a simple toast',
179+
' </div>',
180+
'</div>'
181+
].join('')
182+
183+
const toastEl = fixtureEl.querySelector('.toast')
184+
const toast = new Toast(toastEl)
185+
186+
setTimeout(() => {
187+
toast._config.autohide = false
188+
toastEl.addEventListener('shown.bs.toast', () => {
189+
expect(toast._clearTimeout).toHaveBeenCalled()
190+
expect(toast._timeout).toBeNull()
191+
done()
192+
})
193+
toast.show()
194+
}, toast._config.delay / 2)
195+
196+
spyOn(toast, '_clearTimeout').and.callThrough()
197+
198+
toast.show()
199+
})
173200
})
174201

175202
describe('hide', () => {

0 commit comments

Comments
 (0)