What could be causing my code to lag by 2 ticks instead of just 1?

Apologies for any spacing issues.

Player = {
    move: function(cycle, opponent) {
      switch(cycle.current_direction) {
      case 'up':
        cycle.y -= cycle.height;
        break;
      case 'down':
        cycle.y += cycle.height;
        break;
      case 'right':
        cycle.x += cycle.width;
        break;
      case 'left':
        cycle.x -= cycle.width;
        break;
    }
    if (this.checkCollision(cycle, opponent)) {
      Game.stop(cycle);
    }
    coords = cycle.x + ',' + cycle.y;

    if(cycle.history.length > 0){
        var prev_position = cycle.history[cycle.history.length - 1]
        var pp_split = prev_position.split(',');
        var pp_x = pp_split[0]
        var pp_y = pp_split[1]

        var coords_split = coords.split(',')
        var x = coords_split[0]
        var y = coords_split[1]

        if(parseInt(x) == (parseInt(pp_x) - 4)){
            for(i=x;i>x-4;i--){
                cycle.history.push(i+','+y)
            }
        }else if (parseInt(x) == (parseInt(pp_x) + 4)){
            for(i=x;i<x+4;i++){
                cycle.history.push(i+','+y)
            }
        }else if (parseInt(y) == (parseInt(pp_y) - 4)){
            for(i=y;i>y-4;i--){
                cycle.history.push(x+','+i)
            }
        }else if (parseInt(y) == (parseInt(pp_y) + 4)){
            for(i=y;i<y+4;i++){
                cycle.history.push(x+','+i)
            }
        }else{
            console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ERROR')
            console.log('cycle.history.length - 1 :' + (cycle.history.length - 1))
            console.log('x: ' + x, 'pp_x: ' + pp_x)
            console.log('y: ' + y, 'pp_y: ' + pp_y)
        }
    }else{
        cycle.history.push(coords);
    }    
},

}

There is a slight delay in my code execution, as indicated by the console log here: https://i.sstatic.net/tmIp2.jpg

The desired outcomes are:

  1. (cycle.history.length-1) should increase by one every loop (currently it stays at 0);
  2. x should be either 4 more or 4 less than pp_x, and y should be either 4 more or 4 less than pp_y in each loop

Given conditions:

  1. Players move 4 pixels every loop (100ms)
  2. A loop iteration takes 1 tick

Any assistance would be greatly appreciated. Thank you.

Answer №1

It seems like only the final nested conditional else block in its parent conditional block is being logged by the console. Within this conditional block, no information is added to the history property.

The screenshot only shows the following block being executed:

console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ERROR')
console.log('cycle.history.length - 1 :' + (cycle.history.length - 1))
console.log('x: ' + x, 'pp_x: ' + pp_x)
console.log('y: ' + y, 'pp_y: ' + pp_y)

No data is pushed to cycle.history within this specific block.

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

The button's background color will vanish if you click anywhere outside the button or on the body of

Struggling with a tabpane created using HTML, CSS, and JavaScript. The problem arises when the background color of the active tab's button disappears upon clicking outside the button or on the body. While switching between tabs, I can change the color ...

Challenges with 'this' reference in a requireif causing Vuelidate complications

     Need help with vuejs component using vuelidate and validations:     validations: {      invoice: {          dueDate: {              required,          },          tax: {              require ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Extracting information from Javascript on an HTML webpage

The text snippet provided is a segment of an HTML page. I am looking to extract the data but unsure about the most effective method to do so. JSON would be ideal, however, I am uncertain if this content can be converted into JSON format. Is Regular Expre ...

Is it possible that bitwise left shifts in JavaScript ES6 (<<) become cyclical after surpassing a shift of 63?

From my understanding of the << bitwise left operator in JS (ES6), the void to the right is typically filled with zeros. However, through observation in both V8 and JSC, it appears that the set bits suddenly reappear when we shift by 64 or more. (2 ...

Shall we Combine JavaScript Files with Import and Require Statements?

Apologies for the vague description, I am trying to be concise while acknowledging my limited understanding and potential incorrect assumptions. I currently have a website that consists of one large HTML file with scripts defined in-line within <script ...

Mastering Meteor: Techniques for Manipulating Mongodb Data in Real Time Display

Within my Meteor application, I have accomplished the successful publication of data from the server and its subscription on the client side. Instead of directly displaying raw data on the client's screen, I am interested in performing some calculatio ...

Transforming a JavaScript component based on classes into a TypeScript component by employing dynamic prop destructuring

My current setup involves a class based component that looks like this class ArInput extends React.Component { render() { const { shadowless, success, error } = this.props; const inputStyles = [ styles.input, !shadowless && s ...

Looking to display a gif when a user clicks a button

I need help with making a spinner gif hidden in Unbounce and then show when the user clicks a button. The button is labeled #lp-pom-button-279 and the image is labeled #lp-pom-image-288 My attempts to use JS and CSS have resulted in the gif being either a ...

Why isn't the jQuery colorbox popup appearing when triggered by the $.ajax() function?

I am currently facing an issue where I am trying to display a hidden colorbox popup using the $.ajax() method's success function, but it is not showing up. Interestingly, this had worked fine in a previous implementation where I used the data attribut ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

v-autocomplete not displaying full list of items in selection dropdown

I have a question regarding sending an array with values ranging from 1 to 100 on the v-autocomplete item props. However, when scrolling through the list, only numbers up to 40-50 are visible. <template> <v-app> <v-container> ...

Is it possible to import Vue directly from the "/path/to/vue.js" file without using npm or NodeJs?

Is it possible to build a web app using just a single index.js file and importing other available files like shown in this image: https://i.stack.imgur.com/02aFF.png encountering the error message: import not found: default Do you have to use Vuejs wit ...

How to replace text using jQuery without removing HTML tags

One of the functions in my code allows me to replace text based on an ID. Fortunately, this function is already set up and working smoothly. $('#qs_policy .questionTitle').text("This text has been updated"); However, there is another ...

Is it possible to retrieve data from a promise using the `use` hook within a context?

Scenario In my application, I have a component called UserContext which handles the authentication process. This is how the code for UserProvider looks: const UserProvider = ({ children }: { children: React.ReactNode }) => { const [user, setUser] = ...

Is it possible to continuously refresh a DIV element?

After spending the past 4 or 5 hours scouring Stack and various other resources, I am still unable to find a solution to my problem. The issue at hand involves an Iframe within a page that displays 5 lines of information fetched from a database. This info ...

Can anyone help with displaying a PNG image in Vue/Node/Express? I am struggling to show the image that I sent from a Node.js server to a Vue app client

In my Node/Express application, I've set up a route like this: app.get('/get-image', function(req, res) { ... res.sendFile(path.join(__dirname, '..', account.profileImg)); }) Now in my client-side Vue app, I'm tryi ...

Arranging a string array in JavaScript according to an integer array

Looking at the provided javascript arrays: letterArray ['a', 'e', 'i', 'o', 'u'] We also have another array that corresponds to it: valueArray [12, 22, 7, 7, 3] The goal is to sort the valueArray into: ...

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...