我正在尝试创建一个if语句,该语句在称为函数时设置超时:
var timeOutID;
if (//function1 is called) {
timeOutID = setTimeout(function1, 30000);
}
这个想法是,该函数在30秒后重复调用,但是如果调用函数,可以在任何时候重置超时(例如,单击一个按钮)。如何实现?非常感谢。
当您想以设定的间隔重复进行某些操作时,setInterval
可能是更好的方法。如果您不取消,它将在每个X毫秒之后调用方法。
这是每当单击按钮时重置间隔的一个基本示例。在日志中,您会看到,当您不单击按钮时,每5秒就会出现新日志行。当您单击按钮时,下一行将需要更长的时间出现,之后它们将每5秒再次出现。
我使用了5秒而不是30,因此您不必等待那么长时间就可以看到按下按钮的效果。
const
resetButton = document.getElementById('reset'),
confirmationMessage = document.getElementById('confirmation'),
intervalDuration = 5000;
let
intervalId = null
lastCallTime = new Date();
function resetInterval() {
// Stop the current interval...
clearInterval(intervalId);
// and start a new interval.
startInterval();
}
function startInterval() {
// Set an interval, it will call logTimeSinceLastCall every X seconds.
intervalId = setInterval(() => {
logTimeSinceLastCall();
}, intervalDuration);
}
function logTimeSinceLastCall() {
// Hide the message that the interval has been reset.
confirmationMessage.classList.add('hidden');
const
// Get the current time.
now = new Date(),
// Substract the time from the last call, the difference is the number of milliseconds passed.
diff = now.getTime() - lastCallTime.getTime();
// Log a line to the console for some visual feedback.
console.log(`Last call was ${diff}ms ago`);
// Update the time stamp of the last time this method was called.
lastCallTime = now;
}
function onResetClicked(event) {
resetInterval();
// Show the message that the button has been clicked.
confirmationMessage.classList.remove('hidden');
}
// Whenever the button is clicked, reset the interval.
resetButton.addEventListener('click', onResetClicked);
// Start the initial interval.
startInterval();
.hidden {
display: none;
}
<button type="button" id="reset">Reset interval</button>
<p id="confirmation" class="hidden">
The interval has been reset.
</p>