【发布时间】:2021-03-12 07:48:51
【问题描述】:
我在 Angular.js 中有一个函数来确定用户是处于非活动状态还是处于活动状态。当用户处于活动状态时,我想在一段时间后执行一个功能。
我让它工作了,但该函数当前运行的数量与执行的事件相同。 如何保证这个函数每次执行一次?
.run(function($timeout, $document) {
// console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 120000;
// Start a timeout
var TimeOutThread = $timeout(function() {
LogoutByTimer();
}, TimeOutTimerValue);
var bodyElement = angular.element($document);
angular.forEach(
[
'keydown',
'keyup',
'click',
'mousemove',
'DOMMouseScroll',
'mousewheel',
'mousedown',
'touchstart',
'touchmove',
'scroll',
'focus'
],
function(EventName) {
bodyElement.bind(EventName, function(e) {
TimeOutResetter(e);
});
}
);
function LogoutByTimer() {
console.log('Logout');
}
function TimeOutResetter(e) {
console.log(' ' + e);
$timeout(function() {
console.log('run this once ');
}, 2000);
// Stop the pending timeout
$timeout.cancel(TimeOutThread);
// Reset the timeout
TimeOutThread = $timeout(function() {
LogoutByTimer();
}, TimeOutTimerValue);
}
})
这是关于函数TimeOutResetter(e) 中的console.log('run this once')。
如何运行一次?
【问题讨论】:
-
我认为简单的方法是创建一个值为 false 的全局 var,然后为您想要运行 1 次的部分创建一个 if 并查看是否为 false 并运行它,当您运行它时将 var 更改为true 所以下次不符合条件
-
是的,看起来不错,让我试试。
-
@SimoneRossaini no 没用,试过
var runOnce = false; $timeout(function() { if (!runOnce) { console.log('send session'); } runOnce = true; }, 2000); -
如果您想为源代码中的多个函数实现相同的行为(仅运行一次),您可能希望将行为抽象为包装函数,使您能够“一次化”任何函数-the-fly,比如
myFunctionOnce = once(myFunction)。请参阅:davidwalsh.name/javascript-once。
标签: javascript angularjs dom-events