在页面上停留3分钟后显示警告

时间:2013-04-22 15:40:16

标签: javascript jquery ajax

我正在使用测试的php页面。测试的最长时间为1小时,但会话在10分钟不活动后超时。在超时时,测试页面不刷新或重定向...它保持不变,但是当用户在测试结束时点击“查看结果”按钮时,他将被注销并且他的结果不会被注册。

我只需要 - [在页面上不活动3分钟后] - 显示警告信息。 如果在显示消息后,用户在页面的任何位置进行鼠标移动 - 或点击 - ,计时器将重置而不刷新页面。

如果即使在显示警告消息后,用户没有移动鼠标或点击7分钟,该消息显示“您已经注销”。

我是编程的初学者,但我想这很简单,在3分钟和10分钟不活动后显示2条消息,鼠标移动或点击时都会重置计时器。

有人可以帮我解决这个问题吗?谢谢!

4 个答案:

答案 0 :(得分:3)

var timeout;

document.onmousemove = resetTimer;
document.onclick = resetTimer;

function resetTimer = function() {
  clearTimeout(timeout);
  timeout = setTimeout(function(){alert("3 minute warning");}, 3*60*1000);
}

正如@Elzo Valugi指出的那样,您的服务器将无法验证您在客户端执行的任何操作,因此如果这很重要,您还需要添加服务器端代码。

答案 1 :(得分:2)

var timeoutWarn;
var timeoutLogout;

// Set the timer
resetTimer();

// Reset the timer
document.onmousemove = resetTimer();
document.onclick = resetTimer();

function resetTimer = function() {
    timeoutWarn = window.setTimeout(function() { 
        // create warning element.
    }, 180000);

    timeoutLogout = window.setTimeout(function() { 
        // ajax to process logout
        alert('You have been logged out');
    }, 420000);
}

答案 2 :(得分:0)

如果你真的想要正确,那就假设任何客户端都是假的并忘记了JS解决方案。唯一正确的方法是服务器端。但遗憾的是,HTTP请求是无状态的,这意味着您不确切知道客户端正在做什么以及他是否仍处于活动状态。你可以做的是在每个请求上更新会话信息服务器端,并且每分钟就有一个cron作业,作为过期会话的垃圾收集器。

答案 3 :(得分:0)

这应该允许您在不修改核心计时器逻辑的情况下调整区域和实际毫秒/动作

var $area = $(document),
    idleActions = [
        {
            milliseconds: 3000, // 3 seconds
            action: function () { alert('Warning'); }
        },
        {
            milliseconds: 3000, // 3 + 3 = 6 seconds
            action: function () { alert('Logout'); }
        }
    ];


function Eureka (event, times, undefined) {
    var idleTimer = $area.data('idleTimer');
    if (times === undefined) times = 0;
    if (idleTimer) {
        clearTimeout($area.data('idleTimer'));
    }
    if (times < idleActions.length) {
        $area.data('idleTimer', setTimeout(function () {
            idleActions[times].action(); // run the first action
            Eureka(null, ++times); // setup the next action
        }, idleActions[times].milliseconds));
    } else {
        // final action reached, prevent further resetting
        $area.off('mousemove click', Eureka);
    }
};

$area
    .data('idle', null)
    .on('mousemove click', Eureka);

Eureka(); // start the first time

jsFiddle:http://jsfiddle.net/terryyounghk/wMZJA/

相关问题