Issues with multikeypress functionality in Javascript causing performance hiccups

Is it possible for this code to take two inputs directly from the browser window? If I press q, then 4000 should be incremented by 1. Similarly, if I press w, then 3000 should be incremented by 1. When both keys are pressed at the same time, both numbers should be incremented. However, when I release one of the keys (let's say q), the other key (w) stops working as well. Is my logic incorrect or does the keydown function work in this manner? Any possible solutions would be appreciated. Thank you.

HTML:

<div id="num1">3000</div>
<div id="num2">4000</div>
<div >w =<span id="w"></span></div>
<div >q =<span id="q"></span></div>
<div>Last raised key=<span id="deleted"></span></div>

JS:

<script>
    keylogger={};

    window.addEventListener("keydown",function(e){
        keylogger[e.key]=true;
        document.getElementById("w").innerHTML=keylogger['w'];
        document.getElementById("q").innerHTML=keylogger['q'];
        div1=document.getElementById("num1") ;
        div2=document.getElementById("num2") ;

        if(keylogger['w'] && keylogger['q']){
            value=parseInt(div1.innerHTML);
            div1.innerHTML=++div1.innerHTML;
            value=parseInt(div2.innerHTML);
            div2.innerHTML=++div2.innerHTML;
        }
        if(keylogger['w']){
            value=parseInt(div1.innerHTML);
            div1.innerHTML=++div1.innerHTML;
        }
        if(keylogger['q']){

            value=parseInt(div2.innerHTML);
            div2.innerHTML=++div2.innerHTML;
        }
    });
    window.addEventListener("keyup",function(e){
        document.getElementById("deleted").innerHTML=e.key;
        delete keylogger[e.key];
    })


</script>

Answer №1

Unsophisticated solution: Grab this code and execute it. It will get the job done, but it requires some tidying up. The reason your code isn't functioning as expected is due to the interruption of events when releasing one key out of two simultaneously pressed.

Tips for a more refined solution: While this solution works, there is room for improvement. To enhance its elegance, consider assigning the setInterval function to a variable and invoking it within the addEventListener "keydown". At that point, ensure that initialization occurs only once by checking if it has already been initialized. If it's already running, take no action.

In the addEventListener "keyup", remove the variable function with clearInterval to stop the setInterval from running unnecessarily.

Keep in mind that in your scenario, you'll have two variables, 'w' and 'q', where you assign the setInterval function - possibly in an array like how you handle keyLogger = {} / [].

Untidy code:

<html>
<head><title>2 key press</title></head>
<body>
<div id="num1">3000</div>
<div id="num2">4000</div>
<div >w =<span id="w"></span></div>
<div >q =<span id="q"></span></div>
<div>Last raised key=<span id="deleted"></span></div>
<script>
keylogger={};

window.addEventListener("keydown",function(e){
    keylogger[e.key]=true;
    setKeyLogger();
});

window.addEventListener("keyup",function(e){
    document.getElementById("deleted").innerHTML=e.key;
    delete keylogger[e.key];
    setKeyLogger();
})

function setKeyLogger() { 
    document.getElementById("w").innerHTML=keylogger['w'];
    document.getElementById("q").innerHTML=keylogger['q'];
}

setInterval(function(){
    div1=document.getElementById("num1") ;
    div2=document.getElementById("num2") ;

    if(keylogger['w'] && keylogger['q']){
        value=parseInt(div1.innerHTML);
        div1.innerHTML=++div1.innerHTML;
        value=parseInt(div2.innerHTML);
        div2.innerHTML=++div2.innerHTML;
    }
    else if(keylogger['w']){
        value=parseInt(div1.innerHTML);
        div1.innerHTML=++div1.innerHTML;
    }
    else if(keylogger['q']){
        value=parseInt(div2.innerHTML);
        div2.innerHTML=++div2.innerHTML;
    }
 }, 250);

</script>
</body>
</html>

Answer №2

It seems that the issue lies within your if else condition. When both keys w and q are pressed simultaneously, all conditions evaluate to true. To address this, consider using an else statement in your JavaScript code like this:

<script>
keylogger={};

window.addEventListener("keydown",function(e){
    keylogger[e.key]=true;
    document.getElementById("w").innerHTML=keylogger['w'];
    document.getElementById("q").innerHTML=keylogger['q'];
    div1=document.getElementById("num1") ;
    div2=document.getElementById("num2") ;

    if(keylogger['w'] && keylogger['q']){
        value=parseInt(div1.innerHTML);
        div1.innerHTML=++div1.innerHTML;
        value=parseInt(div2.innerHTML);
        div2.innerHTML=++div2.innerHTML;
    }
    else if(keylogger['w']){
        value=parseInt(div1.innerHTML);
        div1.innerHTML=++div1.innerHTML;
    }
    else if(keylogger['q']){

        value=parseInt(div2.innerHTML);
        div2.innerHTML=++div2.innerHTML;
    }
});
window.addEventListener("keyup",function(e){
    document.getElementById("deleted").innerHTML=e.key;
    delete keylogger[e.key];
})


</script>

Answer №3

Perhaps the issue lies in how the Operating System handles a series of interrupts.

Give this a try:

Example 1:

  1. Hold down the key "q"
  2. Hold down the key "w"
  3. Release the key "w"

Example 2:

  1. Hold down the key "q"
  2. Hold down the key "w"
  3. Release the key "q"

Observations: You'll see that in Example 1, both counters stop incrementing BUT in Example 2, it functions correctly.

I speculate that because pressing and releasing keys generate separate interrupts for the processor, the order of these interrupts is crucial. The interrupt triggered when a key is pressed likely expects a release interrupt for that same key.

For more details on how interrupts function:

This is an attempt to explore potential solutions for the issue. If I've missed the mark entirely, we can rule out the aforementioned as the root cause

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Delaying Variable Assignment in Node.js until Callback Function Completes

I am currently working with Node.js, Express, MongoDB, and Mongoose in my project. One specific task involves fetching the largest id number of a document from the MongoDB database and passing it back to the program. To better organize my code, I moved thi ...

What is the best way to retrieve an object instead of an array?

When attempting to retrieve a JSON Object, I unexpectedly received an array instead. My query is based on the primary key, so I anticipate only one result. This is my current method : router.get("/student_info/:id", (req, res, next) => { connecti ...

Combine elements from two separate arrays

Is there an efficient method for combining objects from two arrays into a new list in JavaScript? a = [{a:1, b:2, c:3}, {d:1, e:4, f:2}] b = [{m:1, n:2, o:4}, {r:1,s:3,u:5}, {k:1,j:4,f:8}] z = [{a:1, b:2, c:3, m:1, n:2, o:4}, {d:1, e:4, f:2, r:1,s:3,u:5}, ...

Ways to deactivate dates that come after today's date

Having a bit of trouble with my datepickers in two different views. I have written code to disable dates after the current date, and it works for the first view but not the second. This code snippet works: var yesterday = new Date(); yesterday.setTime(ye ...

Ways to create a clickable image without any hovering disruptions

I'm currently working on my first website using CSS3, HTML, and JS. Once I finish this version, I plan to switch to bootstrap after ironing out the bugs. However, I've hit a roadblock and could use some help. Here is the js fiddle link: https:// ...

Redesigning the reset Zoom feature of HighCharts using a button inspired by Material UI styling

Currently, I am developing a project that incorporates HighCharts and Material UI for the user interface design components. I am wondering if there is a method to substitute the default HighChart reset Zoom button with the Material UI button component? ...

Request validated even though _RequestVerificationToken was not included in the AJAX request

Implementing HtmlAntiForgeryToken in an MVC application involves adding @Html.AntiForgeryToken() on the .cshtml page and including the [ValidateAntiForgeryToken] attribute in the controller. When making an AJAX POST call to the controller, it is crucial to ...

The input value is displaying one value, but the output is showing a different value

I am encountering a unique issue and could really use some assistance. <input class="testVal" type="number" id="GT_FIRING_TEMPERATURE" value="-17" name="degC" onchange="angular.element(this).scope().unitConversion(value,name, id)"> Despite the valu ...

Adjusting the Color of the Checkbox when Selected

<div class="btn-group" data-toggle="buttons"> <label class="btn btn-success"><input type="checkbox"> Low </label> <label class="btn btn-warning"><input type="checkbox"> Medium </label> <label class ...

"Troubleshooting a callback problem in jQuery involving JavaScript and AJAX

UPDATE3 and FINAL: The problem has been resolved with the help of Evan and meder! UPDATE2: To clarify, I need the existing function updateFilters(a,b) to be called, not created. My apologies for any confusion. The issue with the code below is that udpate ...

What is the best way to stop a select menu option from being highlighted once it has been clicked on?

Is there a way to prevent the highlighting of selected options in a <select> menu when a user makes a selection? <select id="my_select_menu"> <option id="1">Option 1</option> // I do not want this option to be highlighted ...

What is the best way to find the index of the element in an array that is closest in

I am working with an array of objects in JSON, and I need to find the index of the object in the array that has the closest number of days to a given value. Is there a built-in function in jQuery or JavaScript that can help me with this? If not, how can I ...

Ways to prioritize HTML5/CSS3 navigation menu above the content

I am attempting to position my navigation menu on top of the content. Despite using z-index and overflow = visible, the desired effect is not achieved. I want to avoid setting the position relative as it will push the content downwards. Simply put, I want ...

Bring in Bootstrap and the Carousel plugin using Webpack Encore

Currently, I am tackling an issue within my Symfony project that involves Webpack Encore and the loading of Bootstrap and the Carousel plugin. The problem may stem from how I import Bootstrap, as it seems to partially work when I import the file like this ...

Disappearing a menu list while zooming in on a page: The art of vanishing navigation

[QUESTION] Is there a way to make the Menu List disappear when zooming in on a webpage? For example: <-- Normal Page [No Zoom] --> [Logo] Profile Gallery Guestbook <-- Zoom In 120% --> [Logo] Profile Guestbook <-- Zoom In 150% --> ...

Are you wondering about the correct way to install eslint-config-airbnb without encountering any "UNMET PEER DEPENDENCY"

➜ beslint git:(master) ✗ eslint -v v3.15.0 ➜ beslint git:(master) ✗ npm install -g eslint-config-airbnb eslint-plugin-jsx-a11y eslint-plugin-import eslint-plugin-react /Users/next/.nvm/versions/node/v7.5.0/lib ├── UNM ...

Delayed callback on blur

I am developing an AutoComplete feature in React that displays a list of suggested completions as the user types into a text box. When a suggestion is clicked, it should trigger a callback function, and the dropdown should disappear when the text box loses ...

What is the best way to incorporate background color in Boostrap version 5.2?

Struggling to add a background color while working with Bootstrap 5.2? It appears that no matter what I try, whether it's adding CSS directly or using classes like bg-primary, nothing seems to work. I'm attempting to set a background color in Bo ...

Is the next method in the .then chain called only after the completion of setState?

I'm currently facing an issue with the execution order of methods in my React app: The problem is that the createQuestions() function is running before the findEmployeeId() method is completed. I believed that the .then should ensure it waits for the ...

Embed script tags into static HTML files served by a Node.js server

Looking to set up a Node server where users can request multiple pages from a static folder, and have the server inject a custom tag before serving them. Has anyone had success doing this? I've tried with http-proxy without success - not sure if a pro ...