JavaScript keydown events seem to exhibit an unusual one-second delay in triggering subsequent events after the initial event

I'm currently working on implementing character movement within a scene using Vue.js.

For this purpose, I have set up key bindings for both left and right buttons:

  created () {
    window.addEventListener('keyup', this.keyup)
    window.addEventListener('keydown', this.keydown)
  }

Below are the methods associated with these key events:

    keydown (e) {
      if (e.keyCode === 37) this.onWalkLeftPressed()
      if (e.keyCode === 39) this.onWalkRightPressed()
    },

    keyup (e) {
      if (e.keyCode === 37) this.onWalkLeftReleased()
      if (e.keyCode === 39) this.onWalkRightReleased()
    }

My goal is to enable instant character movement upon pressing and holding down a key, with no delay between actions. However, what I am experiencing is that once a key is pressed, there is an initial event fired followed by a slight delay of approximately 500ms before consecutive events are triggered until the key is released.

Is this behavior inherent to browsers, and do you have any suggestions on how I can override it to ensure seamless event firing without any interruptions?

You can view the current setup here:

https://i.sstatic.net/3qTKV.jpg

Answer №1

It's common for there to be a delay in key events.

For optimal gaming performance, it's recommended to handle key states using the keydown and keyup events and updating the position at set intervals.

In frameworks like vue.js, you can achieve this by setting up event listeners and checking key states periodically. Here is an example (JSFIDDLE DEMO)

 // Vue.js code snippet
new Vue({
  keys: {}, // Define keys outside reactive data 
  data: { // Your data here } 
  created () {
    window.addEventListener('keyup', this.keyup);
    window.addEventListener('keydown', this.keydown);
    
    setInterval(this.customKeysChecker, 20); // Check keys every 20ms
  },
  methods: {
    keydown (e) {
        this.$options.keys[e.keyCode] = true;
    },
    keyup (e) {
        this.$options.keys[e.keyCode] = false;
    },
    customKeysChecker() {
      const { keys = {} } = this.$options;
      
      if (keys[37]) this.onWalkLeftPressed(); // Perform action when left key is pressed
      if (keys[39]) this.onWalkRightPressed(); // Perform action when right key is pressed
    },

    onWalkLeftPressed() { // Handle code for walking left },
    onWalkRightPressed() { // Handle code for walking right }
  }
})

Check out these helpful links for more information:

  • How to remove key press delay in JavaScript
  • Fixing delay in JavaScript keydown events

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

Facing the issue of not being able to overwrite the default initialized data (variable) in VUE.JS 2 when using the

Situation I created a generic modal component that uses a global bus (empty VUE instance) to communicate with the modal component from any other component that utilizes it. Problem In the Mounted() or Created() hook for the Modal.VUE component, I am att ...

What is the method for including an inner wrapper around an element in Angular?

Is there a way to create an Angular directive that adds an inner wrapper to a DOM element without replacing the inner content? I have tried implementing one, but it seems to be replacing instead of wrapping the content. (view example) Here is the HTML sni ...

Content duplication in Three.js with WebGL

I am currently working on a Website that features WebGL content. I have successfully implemented a div element to showcase the WebGL. Now, my goal is to display this content in multiple divs on the same page, with identical animations across all divs. How ...

Using JavaScript within HTML documents

Need help with inserting JavaScript code from Google: <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1362706866260-0'); }); </script> into existing JavaScript / HTML code: va ...

Is it beneficial to display three.js on a <canvas> rather than a <div>?

I have come across examples in three.js that use: renderer = new THREE.WebGLRenderer( { canvas: document.querySelector( 'canvas' ) } ); This relates to a <canvas></canvas> element. On the contrary, there is another method: rendere ...

Utilizing Apollo and Vue.js to make GraphQL queries with multiple aliases

My Strapi backend is causing me some trouble as I attempt to fetch data from a single collection type into my Vue.js project using Apollo. Everything works smoothly with a single alias, but I'm facing difficulties when trying to work with multiple ali ...

Do API applications require a session to function properly?

I am in the process of developing an API and I am unsure whether I should implement express-session or a similar tool to handle sessions. app.use(expressSession({ secret: 'Something' }); Moreover, I have been blocking CORS. Is this measure suf ...

Using Express JS to implement a post method for multipart form data transmission

I recently attempted to send form data to my express js server. Below is the code snippet from my pug file: form(action="/profile" method="post" enctype="multipart/form-data") input(type="file" accept="image/*" name="profileimage") input(type="text" nam ...

Having trouble retrieving json data from PHP page using jQuery $.ajax

Having trouble accessing this JSON data in JavaScript, as when I try to alert it the result comes back as undefined Below is the jQuery code snippet: $.ajax({ type: "POST", url: "frmMktHelpGridd.php", data: { labNo: secondElement ...

Is it possible to make changes to a solidity smart contract that has been deployed on the Hedera TestNet?

Currently, whenever there is a change in Solidity, I have to deploy a new contract. This results in losing all the previous data stored in the old contract. Click here for more information ...

Exploring Vue.js with the composition API, delving into the world of "Mixins" and mastering life-cycle hooks

I've been searching everywhere (and coming up empty-handed) for a solution to the following question. In Vue 2.x, I was able to utilize mixins for life-cycle hooks. For example, I could create a file Mixins.js with: export default { created() { ...

What is the best way to set up webpack to exclude a non-existent asset in my scss files?

I am encountering an issue while compiling my scss file. Within the .scss file, I have the following code: body { background-image: url("/static/background.webp"); } The error message I'm seeing is as follows: error in . ...

How to set a default option in a dropdown menu using Angular 4

Many questions have been raised about this particular issue, with varying answers that do not fully address the question at hand. So here we go again: In my case, setting the default value of a dropdown select by its value is not working. Why is that so? ...

Injecting Ajax-loaded content into an HTML modal

Hey there! I'm currently working on a project involving the IMDb API. The idea is that when you click on a film title, a popup should appear with some details about the movie. I've made some progress, but I'm stuck on how to transfer the mov ...

Discover the best correlation among multiple arrays

I am currently developing a chat script that allows users to specify their interests. Upon connecting to the server, the client sends a JSON payload over WebSocket containing information such as ID, hash, auto message, and interests. {"id": int, "hash": m ...

Passing information from the created hook to the mounted hook in VueJS

How can I transfer data from the created function to the mounted function in VueJS? In my VueJS application, the code in my created function is as follows: created: function(){ $.getJSON({ url: 'static/timeline.json', success:function( ...

JSON dataset for advanced charting with ApexCharts

I am encountering difficulties in displaying data from a JSON in my apexchart series. Below is an example of my chart with the desired JSON data that I am struggling to write. var _seed = 42; Math.random = function() { _seed = _seed * 16807 % 21474 ...

What steps can I take to resolve this error when utilizing an npm package in client-side JavaScript?

Just when I thought I was getting the hang of socket.io, I hit a roadblock on the client side. Following my instructor's advice, I installed socket.io-client package for my project. But when I tried to use it in my client-side JS code, I encountered a ...

What is the name of the file that contains a class?

I am curious about identifying the file that called a specific class: database.ts class Database { constructor() { console.log(`I want to know who called this class`); } } server.ts import Database from 'database.ts'; new Databa ...

What could be the source of the error message: "Error: .eslintrc.js: The environment key 'vue/setup-compiler-macros' is not recognized

I am currently working on a sample application using Vue 3 and Typescript. Specifically, I have opted for the new Vue v3.2 setup option within the section of the Vue SFC. Following the guidance from the Vue documentation, I included "vue/setup-compiler-ma ...