用户交互时倒计时计时器增加



考虑这个C#问题:交互时倒计时计时器增加?

我需要一个等价的Javascript。也就是说,以下内容:

问题

我需要在一段时间T之后调用一个回调,但是如果用户交互发生在回调执行之前,那么这个时间T必须增加一些数字X。如何使用Javascript建模?

背景(原因(

我有一个页面转发按钮,点击后页面会增加1。增加页面会导致一些繁重的计算,因此最好只在一个小的时间段后切换页面,这样发送页面按钮的用户就不会让程序进入垃圾箱。

如果我理解正确,您可以简单地清除超时并重新设置它。

clearTimeout(timer);
timer = setTimeout(function(){}, 1000);

我用一个例子做了一个快速代码笔。我希望它能帮助:https://codepen.io/daniti/pen/gjePdo

您可以使用去抖动函数。它设置一个定时器,如果在定时器到期前发生交互,它会删除旧定时器并创建一个新定时器,从而有效地重置时间。示例:

function debounce(fn, delay) { let timerId; return function (...args) { if (timerId) clearTimeout(timerId); timerId = setTimeout(() => { fn(...args); timerId = null; }, delay); } }

您可以使用超时:https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

document.getElementById("spamMe").onclick = doLongAction;
var canDoLongAction = true;
var timeout;
function doLongAction() {
if (canDoLongAction) {
// prevent relaunch of action
canDoLongAction = false

// the action will become available in 2sec
timeout = window.setTimeout(
() => {canDoLongAction = true}, 
2000
)

// you do your long action
alert("hey")
} else {

// if clicked while the timeout is going reset it
window.clearTimeout(timeout);
timeout = window.setTimeout(
() => {canDoLongAction = true}, 
2000
)

}
}
<button id="spamMe">spam me!!</button>

在该示例中,该按钮被阻止,直到您停止点击 2秒

最新更新