【问题标题】:Stop a function in javascript在javascript中停止一个函数
【发布时间】:2018-09-11 18:21:29
【问题描述】:

我实现了一个ResetTime 函数,一旦调用了模态框,我就需要停止该函数。 ResetTime 函数用于会话超时。每次有用户交互时,时间都会重置。

ResetTime函数

function ResetTime() {
    timer = SetLastResetTimeStamp((new Date()).getTime());
} 

function SetLastResetTimeStamp(timeStamp) {
    if (_localStorage) {
        _localStorage[_localStorageKey] = timeStamp;
    } else {
        _lastResetTimeStamp = timeStamp;
    }
}

用户交互检查:

AttachEvent(document, 'click', ResetTime);
AttachEvent(document, 'mousemove', ResetTime);
AttachEvent(document, 'keypress', ResetTime);
AttachEvent(window, 'load', ResetTime);

有没有办法在另一个函数中停止ResetTime 函数?

【问题讨论】:

  • if(modal is open) return;
  • 就像在现实生活中一样,你设置了一个条件。在现实生活中:if driving -> don't hold phone 所以在代码中设置条件也是合乎逻辑的。您需要使用if 语句,然后设置首先应调用函数的条件,或者如果无法在那里设置条件,那么您应该在函数本身中设置它,就像上面写的@Phiter。
  • 也许解决方案是在模式打开时记录时间,并以某种方式更改业务逻辑。否则,一个解决方案将声明一个全局变量(反而是最糟糕的,因为会污染全局命名空间),然后是 if(modalIsOpen){myGlobVar=true}。在 SetLastResetTimeStamp 检查 myGlobVar,如果 false 做本地存储的东西,否则返回。通过这种方式,您不需要分离-重新附加事件。只是一个想法......

标签: javascript


【解决方案1】:

@Phiter 建议的解决方案可行,即您可以在包含标志 modalIsOpen 的范围内定义 ResetTime,然后将其定义如下:

function ResetTime() {
  if (modalIsOpen) {
    return;
  }

  timer = SetLastResetTimeStamp((new Date()).getTime());
}

但是,我认为在打开模式时分离事件并在关闭时重新附加它们会更干净。这将首先阻止该函数被调用。 IE。假设您有两个函数 onModalOpenonModalClose 和一个 DetachEvent 函数,它从各自的 EventTargets 中删除事件:

const onModalOpen = () => {
    DetachEvent(document, 'click', ResetTime);
    DetachEvent(document, 'mousemove', ResetTime);
    DetachEvent(document, 'keypress', ResetTime);
    DetachEvent(window, 'load', ResetTime);

    // ...
}

const onModalClose = () => {
    AttachEvent(document, 'click', ResetTime);
    AttachEvent(document, 'mousemove', ResetTime);
    AttachEvent(document, 'keypress', ResetTime);
    AttachEvent(window, 'load', ResetTime);

    // ...
}

注意:虽然解除绑定和重新绑定事件处理程序并非没有争议(请参阅this answer)。

附带说明,您不能停止 JavaScript(或大多数编程语言)中的函数。您只能阻止它们被执行(例如,通过提前返回、抛出错误或根本不调用它们。)

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 1970-01-01
    相关资源
    最近更新 更多