Check pressing ctrl, shift in javascript

Question:

there is a piece of code executed in a loop. in it you need to check if one of the ctrl or shift keys is pressed. by events is not suitable.

Answer:

Browser JS is not a very multithreaded language. Until your loop finishes executing, the global state will not change.

The easiest option is to interrupt the loop every few iterations, and set the remaining iterations to be executed through window.setTimeout so that global events will work. In global events, catch the shift key, for example as

var shiftDown = false;
var setShiftDown = function(event){
    if(event.keyCode === 16 || event.charCode === 16){
        window.shiftDown = true;
    }
};

var setShiftUp = function(event){
    if(event.keyCode === 16 || event.charCode === 16){
        window.shiftDown = false;
    }
};

window.addEventListener? document.addEventListener('keydown', setShiftDown) : document.attachEvent('keydown', setShiftDown);
window.addEventListener? document.addEventListener('keyup', setShiftUp) : document.attachEvent('keyup', setShiftUp);
Scroll to Top