防止函数被调用

Prevent function from being called

所以我有一个测量连接速度的功能,我每 10 秒就有一个 运行(不需要点击任何地方)。 在其中一种速度较低的情况下,如果为真,它会调用其他函数来打开带有消息的弹出窗口。 我的问题是,速度函数每 10 秒调用一次,所以每 10 秒(如果速度持续很低)它调用弹出窗口,我不希望这样。

我想在第一次速度低时调用弹出窗口,如果速度仍然很低,则在 1 分钟后再次调用。

我的代码是这样的:

 if (speedMbps < low) {
                
                //call the function to open pop-up
                popup_speedtest();
            }

...

function popup_speedtest() {
//make the pop-up opens in vbhtml
$("#alert_speedtest").modal('toggle');
}

我考虑过这样做

setTimeout(function() {
//make the pop-up opens in vbhtml
$("#alert_speedtest").modal('toggle');
}, 60000);

但这不会让弹出窗口第一次打开,而且每次运行该函数时,setTimeout 都会重置。

有什么想法吗?

您想跟踪显示模态的状态。为类似的东西添加一个变量:

let shownModal = false;

然后当您显示模式时,检查 and/or 更新变量并设置 1 分钟计时器以重置变量。像这样:

if (speedMbps < low) {
    if (!shownModal) {
        shownModal = true;
        popup_speedtest();
        setTimeout(function() {
            shownModal = false;
        }, 60000);
    }
}

这样它只在当前状态为 false 时执行逻辑,逻辑是将状态设置为 true,显示模态,并将超时设置为 return状态为false.