0

I'm using Tracking JS to help detect if a users eyes are open and then only playing audio if it detects less than 3 objects, face, mouth, and one eye. I have it mostly convinced and working but the event is tracking and updating the data way too frequently, resulting in a very choppy and jarring experience.

Currently, I have the tracker checking constantly with the tracker on as follows:

  tracker.on('track', function(event) {

      if (event.data.length > 2 ) {
          document.body.classList.add("hide");
          pauseAudio();
      } else {
          document.body.classList.remove("hide");
          playAudio();
      }

Is there a way to run this function less frequently or specify how many times it should run per second?

Peter Lum
  • 143
  • 4
  • 13

1 Answers1

0

You can use some sort of throttling mechanisem, lodash has it build it.

_.throttle, gets a function & time of throttling, and returns a throttled function, so you can use it as:

const handler = function(event) {

      if (event.data.length > 2 ) {
          document.body.classList.add("hide");
          pauseAudio();
      } else {
          document.body.classList.remove("hide");
          playAudio();
      }
};
const throttledHandler = _.throttle(handler, 100); // 100ms
tracker.on('track', throttledHandler);
felixmosh
  • 32,615
  • 9
  • 69
  • 88