如何在重复满足条件时调用一次辅助函数

How to call secondary function once when condition is satisfied repeatedly

本文关键字:一次 函数 调用 满足 条件      更新时间:2024-04-18

功能:

当检测到并满足初始条件时,调用辅助函数。因此,如果"(condition=true)",将调用辅助函数。但是,在条件更改为false之前,次要函数只能调用一次。

因此,正确的行为是:当初始条件仍然为"true"时,不应继续调用辅助函数,正确的行为是,当"condition=true"时只应调用一次,当"condition=false"时,什么都不发生,下一个实例当"condition=true"再次出现时,将再次调用辅助函数一次,直到condition=false。

在这个时间点上,我所做的是,在每个"condition=true"时,它总是调用辅助函数=>location.reload();,这似乎是错误的行为。因此,如果"condition=true"在10秒内为true,则它将在这10秒内每秒刷新一次。

因此,在这一点上,我被困在如何在'condition=true'时只调用'location.reload()'一次,这样它只会刷新页面一次。

因此,我需要关于如何在"条件=真"时只检测一次并调用函数一次的帮助/指导

 var isInterrupt =false;
//Interval to keep asking the backend for sensor value: Hence, if sensor value returns a '1', it will call the function interrupt()
    setInterval(getFeedback,100);
    function getFeedback()
    {
        ajax_getArduinoFeedback("flash.do", "formType=getArduinoFeedback");
    }
    //Method call when data from Arduino is "1"
    function interrupt(){
        //location.reload();
        if (isInterrupt == false)
        {
            isInterrupt = true;
            //When data="1" at the arduino board, Video will reload and start playing
            location.reload();
        }
        isInterrupt=false;
    }

您必须将isInterrupt的记录保存在会话、cookie或localStorage中。

在脚本的开头,它会是这样的:

var isInterrupt = localStorage.getItem("isInterrupt"); /* false by default */

一旦您更改了脚本中的值,也可以在localStorage:中更改它

localStorage.setItem("isInterrupt", "anything");

或者只是删除/取消设置:

localStorage.removeItem("isInterrupt");

因此,完整的例子是这样的:

var savedInterrupt = localStorage.getItem("savedInterrupt");
setInterval(getFeedback,100);
function getFeedback() {
    ajax_getArduinoFeedback("flash.do", "formType=getArduinoFeedback");
}
function interrupt(){
    if( isInterrupt != savedInterrupt ) {
        localStorage.setItem("savedInterrupt", isInterrupt);
        location.reload();
    }
}

根据需要,您可能需要使用会话存储,它只持续一个会话。两者的方法相同。

虽然存储在localStorage中的数据没有过期设置,但存储的数据在会话中当页面会话结束时,存储被清除