I want to perform different operation processes alternately in order with the same key operation

Viewed 137

For example, you can start with a specific key and stop with a click or another key,

// Alt + Shift + ↓  Auto scroll
document.addEventListener("DOMContentLoaded", (l) => {
  var m;
  setInterval(m);
  $(window).keydown((e) => {

    //pattern 1
    if (e.altKey && e.shiftKey && e.keyCode == 40) {
      if (!m) {
        m = setInterval((s) => {
          scrollBy(0, s || 1);
        }, 35);
      }
    }
    $(document).on('click', () => {
      clearInterval(m);
      m = undefined;
    });

    //pattern 2
    setInterval(m);
    if (e.altKey && e.shiftKey && e.keyCode == 40) {
      if (!m) {
        m = setInterval((s) => {
          scrollBy(0, s || 1);
        }, 35);
      }
    }
    if (e.keyCode == 96) { //ten key of「0」key
      clearInterval(m);
      m = undefined;
    }

    //}, false);
  });
});

like this: Attempting to process start and stop with the same key will not work.

In the example below Start with Alt + Shift + ↓,

Stop as well I want to do it with Alt + Shift + ↓. How can I correct it to implement the desired function?

The operating environment uses a third-party extension of the Chrome WEB store.

1 Answers

if i have understood what you want, you want to use the same keys to start and stop so, to do that you have to use a sort of toggle:

var timer;
var last_state = "keyup";
var param = 10;

$(window).on("keydown keyup", (e) => {

  if (e.type == "keyup" && e.which == 40) {
    last_state = "keyup";
  }

  if (e.type == "keydown" && e.type != last_state && e.altKey && e.shiftKey && e.which == 40) {
    last_state = e.type;

    if (!timer) {
      timer = setInterval(() => {
        scrollBy(0, param || 1);
      }, 35);
    } else {
      clearInterval(timer);
      timer = undefined;
    }
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related