JavaScript 时间延迟
JavaScript time delay
我是这个部门的新手,所以我想知道,我可以做一种带有时间延迟的if语句吗?例子:如果某个动作(可能是点击事件)在某个时间段内完成,则重置时间,如果没有完成,则调用函数。
您不能使用 if
语句执行此操作,但可以使用 setTimeout
and clearTimeout
.
这是一个示例,说明如何每 2 秒创建一个函数(console.log
语句)运行,只要您不单击按钮即可。单击该按钮会重置计时器,以便在再次开始记录之前需要再过 2 秒。您可以调整它以适应您需要进行的任何实际工作。
var currentTimeoutId;
function resetTimeout() {
clearTimeout(currentTimeoutId);
currentTimeoutId = setTimeout(function() {
console.log('Too Late!');
resetTimeout();
}, 2000);
}
resetTimeout();
document.getElementById('demo').onclick = function() {
resetTimeout();
};
<button id="demo">Click Me Or Else I'll Log Something!</button>
我是这个部门的新手,所以我想知道,我可以做一种带有时间延迟的if语句吗?例子:如果某个动作(可能是点击事件)在某个时间段内完成,则重置时间,如果没有完成,则调用函数。
您不能使用 if
语句执行此操作,但可以使用 setTimeout
and clearTimeout
.
这是一个示例,说明如何每 2 秒创建一个函数(console.log
语句)运行,只要您不单击按钮即可。单击该按钮会重置计时器,以便在再次开始记录之前需要再过 2 秒。您可以调整它以适应您需要进行的任何实际工作。
var currentTimeoutId;
function resetTimeout() {
clearTimeout(currentTimeoutId);
currentTimeoutId = setTimeout(function() {
console.log('Too Late!');
resetTimeout();
}, 2000);
}
resetTimeout();
document.getElementById('demo').onclick = function() {
resetTimeout();
};
<button id="demo">Click Me Or Else I'll Log Something!</button>