方法 clearTimeout 在重置前不起作用

Method clearTimeout doesn't work before resetting

我正在尝试在此处设置用户空闲超时。似乎一切正常……除了 clearTimeout 函数。事件有效,setTimeout 有效,但无论我做什么,一旦我第一次设置它,就无法阻止它。从我的主控制器的 onBeforeRendering 函数调用方法。调试器没有可见错误。有帮助吗?

   setTimeOut: function () {
    var self = this;

    var timeOut = function userTimeout() { 
     jQuery.sap.log.error("TIMEOUT");
     try {
      if (self.getModel("Global").getProperty("/RecordUnlocked") === true) { 
       self._unlockRecord();
      }
     } catch(e) { 
      jQuery.sap.log.error("TIMEOUT"); 
      
     };
     try {     
      var navHistory = self.getView().getModel("Global").getProperty("/NavHistory"); 
      history.go(navHistory);      
     } catch(e) { 
      jQuery.sap.log.error("TIMEOUT"); 
      
     } 
/*       MessageBox.show(self.getModel("i18n").getResourceBundle().getText("timeOut"), {
      onClose: function(oAction) {*/
    };

    function reset() {
        clearTimeout(timeOut);
        setTimeout(timeOut, 20000); 
    } 
    
    document.onmousemove = reset;
    document.onkeypress = reset;

   }

window.clearTimeout 清除 window.setTimeout 的返回值,而不是您在超时本身中执行的函数。

您拥有的 timeout 变量实际上不是 setTimeout 函数的结果,而是您定义的函数。

通常是这样的

var myTimeoutFunction = _ => console.log('hi');
var myTimeout = window.setTimeout(myTimeoutFunction, 20000);
window.clearTimeout(myTimeout);

作为警告,您自己的函数也称为 setTimeout。在鼠标和按键事件的回调中执行哪一个取决于当前上下文。我想你在这里很幸运,因为事件将 运行 在 window 上下文中,但如果你绑定函数或其他东西,它可能会造成混淆