Show remaining timer after button click

This is refresh current page script…I want to show remaining time when someone click the refresh button…its work very well…but I want to add that option also…kindly help me…

<button id="refresh">Refresh</button>
<script>
  const refreshBtn = document.getElementById("refresh");
  refreshBtn.addEventListener("click", refresh);
  disable();

  function disable() {
    // If `disableRefresh` is truthy...
    if (localStorage.getItem("disableRefresh")) {
      // ...Disables the button and re-enables it after 2 seconds
      refreshBtn.setAttribute("disabled", ""); // Any value makes it true
      setTimeout(enable, 2000); // JavaScript measures times in milliseconds
    }
  }

  function enable() {
    // Removes (boolean) `disabled` attribute and (string) `disableRefresh` item
    refreshBtn.removeAttribute("disabled");
    localStorage.removeItem("disableRefresh")
  }

  function refresh() {
    // Sets `disableRefresh` to a truthy value, and refreshes the page
    localStorage.setItem("disableRefresh", "yep");
    location = location;
  };
</script>

Try this:

<button id="refresh">Refresh</button>
<script>
  const refreshBtn = document.getElementById("refresh");
  refreshBtn.addEventListener("click", refresh);

  if (localStorage.getItem("clickedTime")) {
    // ...Disables the button and re-enables it after 2 seconds
    refreshBtn.disabled = true;
    let loadedTime = new Date();
    let delay = loadedTime.getTime() - localStorage.getItem("clickedTime");
    alert("Remaining time " + (2000 - delay) + " milliseconds");
    if(delay < 2000) setTimeout(enable, 2000-delay); // JavaScript measures times in milliseconds
  }

  function enable() {
    refreshBtn.disabled = false;
    localStorage.removeItem("clickedTime");
  }

  function refresh() {
    // Saves time clicked and refreshes the page
	let now = new Date();
    localStorage.setItem("clickedTime", now.getTime() );
    location = location;
  };
</script>

Note the alert pauses the timeout.

1 Like