JSFiddle - React, Tailwind, and code Playground

HTML

<button id="btn">CLICK ME</button>

JavaScript

function throttle(func, wait, options) {
    var context, args, result;
    var timeout = null;
    var previous = 0;
    if (!options) options = {};
    var later = function () {
      previous = options.leading === false ? 0 : Date.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };
    return function () {
      var now = Date.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  }

  document.getElementById("btn").addEventListener(
    "click",
    throttle(function () {
      console.log("BUTTON CLICKED");
    }, 1000)
  );

  window.addEventListener("message", ({ data }) => {
    if (data.type === "viewer:clear:cache") {
      throttle(test(), 1000);
    }
  });

  function test() {
    console.log("TEST CALLED");
  }

  for (let i = 0; i < 5; i++) {
    window.postMessage({ type: "viewer:clear:cache" }, "*");
  }