我正在开发一个应用程序,在这个应用程序中,我会发出不同的window.postMessage()请求来传递消息。当我使用window.addEventListener('message', cb)收听一条消息时,我会调用另一个函数,但有时我会收到对该函数的多次调用,因为它取决于我发布消息的次数。我创建了一个简单的节流函数,它工作得很好,但不适用于函数调用。例如,假设在1000ms中调用该函数三次时,应该调用该函数一次,而不是三次。
我想知道这是预期的行为,但在我的例子中,函数被调用了三次。
我使用了来自这个答案的节流函数,这也是我创建的示例小提琴,以了解我的意思。
function throttle(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function () {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function () {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
}
document.getElementById("btn").addEventListener(
"click",
throttle(function () {
console.log("BUTTON CLICKED");
}, 1000)
);
window.addEventListener("message", ({ data }) => {
if (data.type === "viewer:clear:cache") {
throttle(test(), 1000);
}
});
function test() {
console.log("TEST CALLED");
}
for (let i = 0; i < 5; i++) {
window.postMessage({ type: "viewer:clear:cache" }, "*");
} <button id="btn">CLICK ME</button>
发布于 2020-09-23 12:47:16
注意,在单击处理程序中,您是如何将throttle的返回值传递给addEventListener的。在消息事件情况下,您将在事件处理程序中调用throttle,并忽略返回值。
您也不是传递一个函数来节流,而是传递test()的返回值。也就是说,您首先调用test,然后将undefined传递给throttle。这就是为什么每次调用消息事件处理程序时都会调用test。
你需要的是:
window.addEventListener("message", throttle(({ data }) => {
if (data.type === "viewer:clear:cache") {
test();
}
}, 1000));throttle返回一个新函数,在接收事件时需要调用该函数。
https://stackoverflow.com/questions/64027876
复制相似问题