clearTimeout不会将计时器置于零

时间:2015-10-23 15:33:10

标签: javascript timer

我研究了许多相关主题,但无法找到解决方案。我想创建一个脚本,由于不活动而将重定向到不同的页面。我尝试过以下脚本的变体无济于事。



$(function () {
    doStuff();
});


function doStuff () {
    var timer = null;
    
    window.onload = resetTimer;
    window.onmousemove = resetTimer;
    window.onmousedown = resetTimer; // catches touchscreen presses
    window.onclick = resetTimer;     // catches touchpad clicks
    window.onscroll = resetTimer;    // catches scrolling with arrow keys
    window.onkeypress = resetTimer;

    function logout() {
       document.getElementById('status').innerHTML = 'the timer reads ' + timer;
    }

   function resetTimer() {
        if(timer){window.clearTimeout(timer);};   
        timer = window.setTimeout(logout, 1000);  // time is in milliseconds
    }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='status'></div>
&#13;
&#13;
&#13;

当发生任何已定义的事件时,它不会将计时器重置为零,而只是增加现有的计时器。尝试运行代码段并移动鼠标等。所有事件都不会清除计时器。

我在Chrome,Firefox和IE中测试了我的脚本。我也设置了一个小提琴:

http://jsfiddle.net/bradsmithcpa/sjxn2s6j/

1 个答案:

答案 0 :(得分:2)

Rocket Hazmatt通过解释'计时器'是一个内部ID来回答我的问题。我误解了timeoutID所代表的含义。