Skip to content

Commit 227858e

Browse files
committed
Only use timers if needed
Fixes #1
1 parent 97ac9c8 commit 227858e

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

simpletoast.js

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* SimpleToast - A small library for toasts
33
*/
44
(() => {
5-
const version = buildVersion(1, 3);
5+
const version = buildVersion(1, 4);
66
if (window.SimpleToast) {
77
if (SimpleToast.version) {
88
if (SimpleToast.version >= version.number) return;
@@ -95,18 +95,30 @@
9595
}
9696
return el;
9797
}
98+
return document.getElementById('AlertToast') || create();
99+
})();
100+
let count = 0;
98101

99-
setInterval(() => { // TODO: don't always run a timer
102+
let timeout = null;
103+
function startTimeout() {
104+
if (timeout) return;
105+
timeout = setTimeout(() => {
106+
timeout = null;
100107
const now = Date.now();
108+
let pending = 0;
101109
toasts.forEach((toast) => {
102-
if (!toast.timeout || now < toast.timeout) return;
103-
// Close toast
110+
if (!toast.timeout) return;
111+
if (now < toast.timeout) {
112+
pending += 1;
113+
return;
114+
}
104115
toast.close();
105116
});
117+
if (pending) {
118+
startTimeout();
119+
}
106120
}, 1000);
107-
return document.getElementById('AlertToast') || create();
108-
})();
109-
let count = 0;
121+
}
110122

111123
function Toast({title, text, className, css = {}, buttons, timeout}) {
112124
if (typeof arguments[0] === 'string') {
@@ -151,7 +163,7 @@
151163
if (!button.text) return;
152164
const elb = document.createElement('button');
153165
if (button.className || className && className.button) {
154-
const clazz = button.className || className.button
166+
const clazz = button.className || className.button;
155167
elb.className = Array.isArray(clazz) ? clazz.join(',') : clazz;
156168
}
157169
elb.innerHTML = button.text;
@@ -182,6 +194,9 @@
182194

183195
root.appendChild(el);
184196
toasts.set(id, toast);
197+
if (timeout) {
198+
startTimeout();
199+
}
185200
return toast;
186201
}
187202

0 commit comments

Comments
 (0)