Skip to content
Advertisement

Having a problem with starting a setTimer for a function and stopping it JavaScript

Hello I want to make it so that I can start and stop a function with a keypress and I’ve been having a problem with setting a timer on my function and I don’t know why the addEventListener is giving me errors like this is not a function or window not defined I tried to switch window with global because I’m using node.js but it still doesn’t work

var refreshIntervalId;

window.addEventListener("onkeydown", keyDown, true);
window.addEventListener("keydown", keyDown);

function keyDown() {
  var e = window.event;
  switch (e.keyCode) {
    case 115:
      start();
      break;
    case 83:
      stop();
      break;
  }
}

function start() {
  stop();
  refreshIntervalId = setInterval(function () {
    var data = Data();
    data.then((result) => {
      console.log(result);
    });
  }, 5000);
}
function stop() {
  if (refreshIntervalId != null) {
    clearInterval(refreshIntervalId);
    refreshIntervalId = null;
  }
}

Advertisement

Answer

Here’s a remake of your original code:

  • Use only the "keydown" Event.
  • Set the itv to undefined inside the stop() function
  • Don’t use evt.keyCode. You’re writing code mainly for developers and a future self. Use evt.key instead, or eventually evt.code (if other keys like ShiftKey matter)
  • Use evt.repeat to check whether the user is long-pressing a key

let itv;
let dummyIndex = 0;
const Data = () => Promise.resolve(`Dummy data ${++dummyIndex}`);

const start = () => {
  stop();
  dummyIndex = 0;
  itv = setInterval(() => {
    Data().then((res) => console.log(res));
  }, 1000);
  console.log("Started");
};

const stop = () => {
  if (!itv) {
    return; // Do nothing (Already stopped).
  }
  clearInterval(itv);
  itv = undefined;
  console.log("Stopped");
};

const keyDown = (evt) => {
  if (evt.repeat) {
    return; // Do nothing on long keydown
  }
  switch (evt.key) {
    case "F4":
      start();
      break;
    case "s":
      stop();
      break;
  }
};

addEventListener("keydown", keyDown);
Click here to focus.<br>
Hit "F4" to Start<br>
Hit "s" to Stop<br>
Or hit "F4" to Restart

PS: needless to say, the above JavaScript is specifically intended for the browser environment, not NodeJS.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement