Run a function when no actions from user for specified time (pure JS)

I’ve got a function that delays javascript load to act on user interaction. Here’s the javascript function:

class LazyLoadScripts {
  constructor(e) {
      this.triggerEvents = e, this.eventOptions = {
          passive: !0
      }, this.userEventListener = this.triggerListener.bind(this), this.delayedScripts = {
          normal: [],
          async: [],
          defer: []
      }, this.allJQueries = []
  }
  _addUserInteractionListener(e) {
      this.triggerEvents.forEach(t => window.addEventListener(t, e.userEventListener, e.eventOptions))
  }
  _removeUserInteractionListener(e) {
      this.triggerEvents.forEach(t => window.removeEventListener(t, e.userEventListener, e.eventOptions))
  }
  triggerListener() {
      this._removeUserInteractionListener(this)
  }
  /* ....... */
  static run() {
      const e = new LazyLoadScripts(["keydown", "mousemove", "touchmove", "touchstart", "wheel"]);
      e._addUserInteractionListener(e)
  }
}
LazyLoadScripts.run();

But, I want this function to run after a specific time (5 sec) if no user interaction happens. How can I do that? Can anyone help me? Please!

Add a setTimeout() call for 5 seconds. If an interaction happens, then in the handler for the event, just cancel the timeout.

Recall that setTimeout() returns a value that can be used to store a reference to the timer. If you set this on the window object, you can essentially cancel the timer from anywhere (using clearTimeout(<that variable>)).

window.noActionTimer = setTimeout(run, 5000);

// Inside some listener (which is triggered when the user interacts within the 5 seconds)
clearTimeout(window.noActionTimer);

So play around with that and you should come up with something pretty quick. :slight_smile:

I can’t play with JavaScript! Can you please add more?

If you have a browser, you can play with JavaScript. Use your devtools if you need to try out some things. This site is for helping you, not doing everything for you. Here is a great video to learn devtools in chrome if you are not familiar with it and how you can use it play with JavaScript.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.