javascript - 如何避免调用 postmessage
问题描述
在我的应用程序中,我具有使用 setInterval 的倒计时功能,如下所示:
this.timer = window.setInterval(() => {
const time_delta = (this.target_date - new Date() ) / 1000
if (time_delta > 0) {
this.days = time_delta / (24 * 3600)
this.hour = time_delta % (24 * 3600) / (3600)
this.minute = (time_delta % (24 * 3600) % (3600)) / 60
this.second = time_delta % 60
} else {
this.days = 0
this.hour = 0
this.minute = 0
this.second = 0
}
if(time_delta <= 1 && time_delta > 0 ){
clearInterval(this.timer);
location.reload();
}
},10000)
现在还有另一个功能完全不同,它继承了 postmessage
(function (window, undefined) {
function MessageChannel(group, targetWindow, origin) {
this._msgNo = 1;
this._group = group;
this._origin = '*' || origin;
this._requestHandler = {};
this._messageQueue = {};
this._targetWindow = targetWindow || window.parent;
window.addEventListener('message', receiveMessage.bind(this), false);
}
MessageChannel.prototype.subscribeRequestMessage = function (msg, callback) {
// Some logic
};
MessageChannel.prototype.unsubscribeRequestMessage = function (msg, callback) {
// Some logic
};
MessageChannel.prototype.postMessage = function (msg, data, timeout) {
// Some logic
};
function receiveMessage(event) {
// Some logic
}
window.Granite = window.Granite || {};
window.Granite.author = window.Granite.author || {};
window.Granite.author.MessageChannel = MessageChannel;
}(this));
我遇到的问题是,只要 setInterval 在倒数计时器中每秒钟执行一次,那么 MessageChannel.prototype.postMessage 函数也会执行。
倒数计时器是 html 页面的 iFrame 中存在的一个组件,该页面还具有 MessageChannel.prototype.postMessage 的代码,并且它可以由我用来构建页面的框架/工具全局使用。每当组件发生变化时,框架都会触发 MessageChannel.prototype.postMessage。在这种情况下,计时器值会发生变化,从而触发 postMessage 调用。我不想执行 MessageChannel.prototype.postMessage 代码。我怎样才能避免这种情况?
解决方案
推荐阅读
- javascript - 托管站点缺少本地 html 文件中的元素
- java - android - 无法从资产文件夹复制数据库:API < 24
- php - 恢复会话密钥,然后将其删除。(php5.6)(解决方法)
- apache-flink - Apache Flink DataStream - 翻滚窗口中的元素计数
- javascript - 谷歌云平台中的多图表选择
- django - 如何在 Django 中加载与选定的多个选项相关的值
- racket - 初学者问题:不能在定义之前引用标识符
- java - 自动更新来自 Android 中 API 服务的片段数据
- android - 手动验证 Firebase otp
- entity-relationship - ER图中的实体和关系