如何避免 setTimeout 被覆盖?
How to avoid setTimeout to be overridden?
我多次调用函数 notifyError()
,并且我试图找到一种方法来避免*每次都覆盖其中的 setTimeout()
。
相反,我想在每次调用 notifyError()
时创建 setTimeout
的新 实例 。
export function notifyError(message) {
...
setTimeout(() => {
notifications.splice(notification.length -1, 1)
}, 3000)
}
我猜想在 ...
代码中,您将 message
放在 notifications
中(直接或在某些包装器中)并且您想知道为什么什么时候你有重叠的调用,错误的通知从 notifications
.
中删除
这是因为每次调用 notifyError
时,它都会安排一个计时器在三秒后触发。三秒后,当该计时器触发时,它会删除 notifications
中的 last 通知,无论该通知是否与对 notifyError
的调用有关。
而是删除添加的通知。例如,如果它只是字符串,你可以这样做:
export function notifyError(message) {
// ...
setTimeout(() => {
const index = notifications.indexOf(message);
if (index !== -1) {
notifications.splice(index, 1);
}
}, 3000)
}
但是如果你放入 notifications
的是一个对象或类似的东西,你将需要 findIndex
和适当的回调(或者保留对象并使用 indexOf
对象)。
我多次调用函数 notifyError()
,并且我试图找到一种方法来避免*每次都覆盖其中的 setTimeout()
。
相反,我想在每次调用 notifyError()
时创建 setTimeout
的新 实例 。
export function notifyError(message) {
...
setTimeout(() => {
notifications.splice(notification.length -1, 1)
}, 3000)
}
我猜想在 ...
代码中,您将 message
放在 notifications
中(直接或在某些包装器中)并且您想知道为什么什么时候你有重叠的调用,错误的通知从 notifications
.
这是因为每次调用 notifyError
时,它都会安排一个计时器在三秒后触发。三秒后,当该计时器触发时,它会删除 notifications
中的 last 通知,无论该通知是否与对 notifyError
的调用有关。
而是删除添加的通知。例如,如果它只是字符串,你可以这样做:
export function notifyError(message) {
// ...
setTimeout(() => {
const index = notifications.indexOf(message);
if (index !== -1) {
notifications.splice(index, 1);
}
}, 3000)
}
但是如果你放入 notifications
的是一个对象或类似的东西,你将需要 findIndex
和适当的回调(或者保留对象并使用 indexOf
对象)。