Sluggish JQuery Animation When Key is Pressed

I have a situation where I am using JQuery to create animation effects on a div element based on arrow key inputs.

However, I am encountering an issue where the animation slows down significantly each time I repeat pressing the arrow key for the current direction.

I tried using $player.stop() and $player.clearQueue() functions to resolve this problem, but they did not work as expected. Any suggestions on how to fix this?

You can access the JSFiddle demonstration of the issue here: https://jsfiddle.net/qb484yp2/

Below is the JavaScript code snippet I am currently using:

$(document).ready(function () {

    var $player = $('#player'),
    $enemy1 = $('#enemy1'),
    $bg = $('#container'),
    playerW = $player.outerWidth(),
    playerH = $player.outerHeight(),
    bgW = $bg.width(),
    bgH = $bg.height(),
    playerX,
    playerY,
    enemySpeed = 1000,
    playerSpeed = 1000,
    direction,
    down = false;

    var targetSound1 = $('#targetSound1')[0];
    targetSound1.loop = true;

    function keypress(e) {

        $player.clearQueue();
        $player.stop()
        if (down) {
            return;
        }
        down = true;

        var playerLeft = $player.css('left');
        var playerTop = $player.css('top');
        var key = e.which || e.keyCode;
        if ([38, 40, 37, 39].includes(key)) {
            e.preventDefault(); // prevent defualts (scrolling)!
        }

        if (key == "37") {
            direction = 'left';
            playerLeft = 0;
        } else if (key == "38") {
            direction = 'up';
            playerTop = 0;
        } else if (key == "39") {
            direction = 'right';
            playerLeft = bgW - playerW;
        } else if (key == "40") {
            direction = 'down';
            playerTop = bgH - playerH;
        }

        $player.animate({
            left: playerLeft,
            top: playerTop
        },
            playerSpeed, 'linear');

    }

    function makeNewPosition($container) {

        // Get viewport dimensions (remove the dimension of the div)
        $container = ($container || $(window))
        var h = $container.height() - 50;
        var w = $container.width() - 50;
        var nh = Math.floor(Math.random() * h);
        var nw = Math.floor(Math.random() * w);

        return [nh, nw];
    }

    function animateDiv() {

        var $target = $($enemy1);
        var newq = makeNewPosition($target.parent());
        var oldq = $target.offset();
        var speed = enemySpeed;

        $($enemy1).animate({
            top: newq[0],
            left: newq[1]
        }, speed, 'linear', function () {
            animateDiv();
        });
    };

    $(document).on('keydown', keypress);
    $(document).on('keyup', function () {
        down = false
    });

    animateDiv();

});

Answer №1

After reviewing your fiddle and experimenting with it, I managed to come up with a solution. Here's the link to the updated fiddle: https://jsfiddle.net/qb484yp2/3/

The idea behind my solution was to prevent unnecessary animations from accumulating and slowing down the process. I realized that if the key triggering an event is the same as the key that triggered the previous event, there was no need to animate the #player div again. By keeping track of the last animation and only allowing the animation to occur when the key changes, we achieved a smoother animation effect.

Here's the snippet of code that made all the difference. For the full implementation, please refer to the fiddle:

if(key==lastKey)
{
return;
}
else
lastKey=key;

Additionally, make sure to remove this line from the code as it halts the animation of the player div:

$player.stop()

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

How to shuffle the elements of an array saved in a JSON file using discord.js

I've been working on a Discord bot as a way to learn more about Javascript. While creating a command that pulls random quotes from an array stored in a separate JSON file, I encountered an issue that has me stumped. var config = require("./settings.j ...

Callback issues in need of resolving

This problem seems like it should have a simple solution, but I think I've been staring at it for too long. Initially, I had this function inline, but now I want to extract it and use it in other parts of my application. However, I'm struggling ...

Is it possible for CSS to accurately crop images by pixels [Sprite Box]?

I attempted to replicate the math used for the previous image cuts and added my own image, but it appears blank. Can you identify where the issue lies? #paymentForm { -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webk ...

What aspects of MongoDB security am I overlooking?

Is it a secure way to connect to Mongo DB by using Node JS, Mongo DB, and Express? Could someone provide an explanation of this code in terms of security? === Many tutorials often only show... var mongoClient = new MongoClient(new Server('localhos ...

Iterating through form elements for validation using jQuery

Is there any way to accomplish this using jQuery? This is the initial setup: <input type='checkbox' class='sk1' /> <input type='text' class='skill1' /> <input type='checkbox' class=' ...

I am unable to incorporate the RobotJS module into my ElectronJS project

Currently, I am working on a Windows desktop application using ElectronJS. My main challenge is integrating the RobotJS module into my project. Despite successfully downloading the module with 'npm install robotjs' and incorporating it into my ma ...

Is it possible for Eslint to give a warning if an import statement is missing?

I'm currently working with nodejs and regular javascript, utilizing eslint to identify errors in my code. However, I have noticed that eslint fails to detect when I forget to import a package into my code. The following example highlights this issue. ...

analyze 2 arrays and identify distinct variances

Consider having two different sets var firstSet = [{"id":1},{"id":3},{"id":5}] var secondSet = [{"id":1},{"id":2},{"id":3},{"id":4}] var missingValues = []; for(var x=0; x < firstSet.length; x++) { for(var y=0; y < secondSet.length; y++) { ...

responsive cascading dropdown.. preassigned value

I've come across this interesting script on a website and it's been working pretty well for me so far. The script can be found at the following link: . However, I have a specific requirement when it comes to setting a certain value for the catego ...

Having Trouble with Navbar Toggler Functionality in Bootstrap 5

I'm currently working on a responsive webpage using Bootstrap 5, and I've encountered an issue with the Navbar. The toggle button isn't functioning properly – nothing happens when clicked. I've tried looking through the official docu ...

Node.js exporting fails due to an undefined variable

When attempting to export variables in Node.js, I keep receiving an undefined error. I'm not sure what the issue is, can anyone provide assistance or suggestions? Here is a snippet from index.js: var test = 10; module.exports.test = test; And here i ...

The presence of inline display causes gaps of white space

Located at the bottom of this webpage is a media gallery. The initial three images comprise the photo gallery, followed by video thumbnails inlined afterwards. However, there seems to be an issue with the alignment of each element within the video gallery. ...

Incorporating a rigged and animated asset into a preexisting scene using Three.js

Currently, I'm developing a browser app similar to Tamagotchi using three.js. However, I've hit a roadblock while trying to implement a hand that can pet the avatar when clicked. The Hand is a rigged Blender model with two animations: idle and p ...

Examining the visibility of a specific element

I am working on a script to determine the visibility of an element and scroll down to it if it is visible. Here is the jQuery code I have tried: var j = jQuery.noConflict(); jQuery(document).ready(function($) { if(j('#element').css(' ...

Displaying genuine HTML content in a React application using Algolia Instantsearch

After setting up a demo app using React with an Algolia search feature, I uploaded some indices into Algolia. The content consists of raw HTML. Is there a way to display this content as real HTML using Algolia? ...

Generate three separate inline blocks and position elements within them without any impact on the neighboring blocks

In my attempt to create three blocks with set height and width, aligned on top/bottom with a couple of elements inside each one, I encountered an issue. Whenever I add additional DIVs to one of the elements (resulting in a different number of DIVs inside e ...

Utilizing jQuery and ajax to invoke an MVC controller

Hi there, I am currently facing an issue with calling a method in my controller using ajax and jquery with parameters Controller: [HttpPost("{Id}")] public ActionResult PostComment(int Id, ShowViewModel model) { } View: I have a button named AddCommen ...

Cluster execution error encountered while utilizing Google Maps in Node.js

Recently, I have started using the node.js platform and I am looking to integrate the googlemap cluster library into my project. However, I am facing issues while trying to run the source code. If you want to explore the googlemaps cluster API, you can fi ...

A method for cycling through parent and child objects in JavaScript (Vue.js) and storing them in an array - how to

I have a JSON object structured like this. const jsonData = { "id": "6", "name": "parent", "path": "/", "category": "folder", "fid": "6", "children": [ { ...

Display a div using Jquery depending on the visibility and checked value of another div

Trying to toggle the visibility of a div based on another div's input has proven to be quite challenging in this scenario. Here is the HTML setup: <div id="main-question"> <div class="form-group"> <div class="form-radios"> ...