每次调用函数时如何设置超时

时间:2017-09-12 09:48:18

标签: javascript if-statement timeout

我尝试创建一个if语句,在调用函数时设置超时:

    var timeOutID;

    if (//function1 is called) {
      timeOutID = setTimeout(function1, 30000);
    }

这个想法是在30秒后重复调用该函数,但是如果调用函数(例如单击按钮),则可以在任何时刻重置超时。如何实现这一目标?非常感谢。

1 个答案:

答案 0 :(得分:0)

当您想要按设定的间隔重复某些事情时,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>
&#13;
&#13;
&#13;