我有以下几点:

window.setTimeout(function() {
    window.location.href = 'file.php';
}, 115000);

如何通过.click功能,在倒计时中途重置计数器?


当前回答

你必须记住超时“Timer”,取消它,然后重新启动它:

g_timer = null;

$(document).ready(function() {
    startTimer();
});

function startTimer() {
    g_timer = window.setTimeout(function() {
        window.location.href = 'file.php';
    }, 115000);
}

function onClick() {
    clearTimeout(g_timer);
    startTimer();
}

其他回答

您可以存储对该超时的引用,然后在该引用上调用clearTimeout。

// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);

// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);

// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);

你必须记住超时“Timer”,取消它,然后重新启动它:

g_timer = null;

$(document).ready(function() {
    startTimer();
});

function startTimer() {
    g_timer = window.setTimeout(function() {
        window.location.href = 'file.php';
    }, 115000);
}

function onClick() {
    clearTimeout(g_timer);
    startTimer();
}

对于NodeJS来说,这非常简单:

const timeout = setTimeout(...);

timeout.refresh();

从文档中可以看出:

timeout.refresh () 将计时器的开始时间设置为当前时间,并重新安排计时器以在先前指定的调整为当前时间的持续时间内调用其回调。这对于在不分配新JavaScript对象的情况下刷新计时器非常有用。

但它在JavaScript中不起作用,因为在浏览器中setTimeout()返回的是一个数字,而不是一个对象。

$(function() {

    (function(){

        var pthis = this;
        this.mseg = 115000;
        this.href = 'file.php'

        this.setTimer = function() { 
            return (window.setTimeout( function() {window.location.href = this.href;}, this.mseg));
        };
        this.timer = pthis.setTimer();

        this.clear = function(ref) { clearTimeout(ref.timer); ref.setTimer(); };
        $(window.document).click( function(){pthis.clear.apply(pthis, [pthis])} );

    })();

});
var redirectionDelay;
function startRedirectionDelay(){
    redirectionDelay = setTimeout(redirect, 115000);
}
function resetRedirectionDelay(){
    clearTimeout(redirectionDelay);
}

function redirect(){
    location.href = 'file.php';
}

// in your click >> fire those
resetRedirectionDelay();
startRedirectionDelay();

这里有一个详细的例子,说明到底发生了什么http://jsfiddle.net/ppjrnd2L/