Search code examples
javascriptjqueryevent-handlingdom-eventstimedelay

JavaScript time delay


I'm a newbie in this department, so I was wondering, can I make a type of if statement with a time delay? Example: if a certain action (maybe a click event) is done within a time period, the time is reset, and if it is not, a function is called.


Solution

  • You can't do this with an if statement, but you can with setTimeout and clearTimeout.

    Here's an example of how you can make a function (a console.log statement) run every 2 seconds as long as you don't click the button. Clicking the button resets the timer so that another 2 seconds will need to pass before it begins logging again. You can adapt this to fit whatever actual work you need to happen.

    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>