如何在我的代码中解决JavaScript经过时间问题

时间:2019-04-28 06:33:48

标签: javascript

我想创建一个JavaScript来计算您5分钟的空闲时间,然后为您提供IDLE status = true并开始计算空闲时间,直到通过移动鼠标重置计时器为止

我的问题是,我既不知道如何计算直到5分钟为止的时间,也不知道如何重新计算时间剩余的时间

我尝试使用超时来激活isInactive()函数,但是随后,我没有发现如何添加该函数启动所用的5分钟+用户空闲的剩余时间,以及时刻保持警惕

对于JavaScript来说我还太陌生,我认为我在声明变量的方式和位置上犯了一个错误


var inOffice = true;



function idleUser() {
    var start = new Date().getTime();
    var idleTime = (new Date().getTime() - start) / 1000;
    window.onload = resetTimer;
    window.onmousemove = resetTimer;
    window.onmousedown = resetTimer;  // catches touchscreen presses as well
    window.ontouchstart = resetTimer; // catches touchscreen swipes as well
    window.onclick = resetTimer;      // catches touchpad clicks as well
    window.onkeypress = resetTimer;

    function isInactive() {
        console.log("You are not active");
        inOffice = false;
        if(idleTime) {
            alert("You've been active for " + idleTIme;
        }
    }

    function resetTimer() {
        clearTimeout(time);
        time = setTimeout(isInactive, 5000)
    }
}

idleUser();

2 个答案:

答案 0 :(得分:1)

我尝试检查您的代码以解决您的问题。 我想解决您的问题,您可以按以下方式更改此代码。

function idleUser() {
    var start = new Date().getTime();
    console.log("You are not active");
    var time = setTimeout(isInactive, 5000)
    window.onload = resetTimer();
    window.onmousemove = resetTimer();
    window.onmousedown = resetTimer();  // catches touchscreen presses as well
    window.ontouchstart = resetTimer(); // catches touchscreen swipes as well
    window.onclick = resetTimer();      // catches touchpad clicks as well
    window.onkeypress = resetTimer();

    function isInactive() {
        console.log("You are not active");
        var idleTime = (new Date().getTime() - start) / 1000;
        console.log(idleTime);
        inOffice = false;
        if(idleTime) {
            alert("You've been active for " + idleTime);
        }
    }

    function resetTimer() {
        clearTimeout(time);
        time = setTimeout(isInactive, 5000);
    }
}
idleUser();

但这不适用于循环操作。 为了做到这一点,我想在“ resetTimer”中删除“ ClearTimeout”功能。

答案 1 :(得分:0)

您的 var getIDCurr = $( element ).id='1523517692376-5f09ae62-8203'; 变量未正确声明:

time