代码之家  ›  专栏  ›  技术社区  ›  Tms91

Javascript:循环直到按下CTRL+C

  •  0
  • Tms91  · 技术社区  · 4 年前

    如何使代码片段循环到 CTRL + C 被按下?

    我从 this thread 指示的代码片段循环直到键 按下。

    如何使其循环直到 CTRL + C 被按下?

    1 回复  |  直到 4 年前
        1
  •  0
  •   Tms91    4 年前

    通过将指示的线程与 this one ,这里有一种方法

    // add the event listener to catch the pressing of CTRL+C
    
    document.body.addEventListener("keydown",function(e){
    
        e = e || window.event;
        var key = e.which || e.keyCode; // keyCode detection
        var ctrl = e?.ctrlKey || (key === 17); // ctrl detection
    
        // if CTRL+C is pressed, stop the loop
        if ( key == 67 && ctrl ) {
            window.clearInterval(interval);
    
            console.log("Ctrl + C was pressed on the browser page (while this one was active).");
            console.log("Loop ends!");     
        }
    
    },false);
    
    
    // define the time interval that elapses between the end and the beginning of the loops
    var x_milliseconds = 1000; // milliseconds
    
    // run a function containing the loop commands, every x_milliseconds
    var interval = setInterval(function() {
        console.log("The code is looping!");
    }, x_milliseconds);
    推荐文章