Pictures acting erratic following the implementation of two setTimeout functions

I encountered an issue while developing a pong game using html/css/javascript. Everything was going smoothly until I introduced a second setTimeout() function.

Here is the snippet of my html code:

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src="player.js"></script>
<script type='text/javascript' src="ball.js"></script>
<script type='text/javascript' src="funcs.js"></script>
<link rel="stylesheet" type="text/css" href="cetrnes.css"/>
</head>
<body>
    <img src="universe-54a.jpg" width="700px" height="525px" onclick="back()"></img>
    <img id="player" src="player1.png" onload="move()"></img>
    <img id="ball" src="ball.png"></img>
</body>
</html>

The css styling information is not relevant to this problem.

Here is the player.js script:

function Player(ID) {
    this.t;
    this.y = 170;
    this.speed = -3;
    this.move = function move() {
        if (this.y > 1 && this.y < 421) {
            this.y += this.speed;
        }
        else if (this.y < 1) {
            this.y = 2;
            this.speed = 3;
        }
        else {
            this.y = 420;
            this.speed = -3;
        }
        document.getElementById(ID).style.top=this.y + "px";
        this.t = setTimeout("this.move()",10);
    }
    this.back = function back() {
        if (this.speed < 0) 
            this.speed = 3;
        else
            this.speed = -3;
    }
}

var player = new Player("player");

The ball.js script is as follows:

function Ball(ID) {
    this.t;
    this.x = 350;
    this.y = 260;
    this.left = true;
    this.bot = true;
    this.acc = 5;
    this.move = function move() {
        if (this.bot)
            this.y -= 3;
        else if (!this.bot)
            this.y += 3;
        if (this.left)
            this.x -= 3;
        else if (!this.left)
            this.x += 3;
        document.getElementById(ID).style.top = this.y + "px";
        document.getElementById(ID).style.left = this.x + "px";
        this.t = setTimeout("this.move()",10);
    }
}

var ball = new Ball("ball");

Finally, here is the funcs.js script:

function move() {
    player.move();
    ball.move();
}

function back() {
    player.back();
}

After implementing both the player and ball movement functions simultaneously, the player starts behaving erratically by moving up and down rapidly, while the ball flies off the screen uncontrollably. Despite the unconventional coding approach, it worked fine individually for each element. Your guidance in resolving this issue would be greatly appreciated. Thank you!

Answer №1

When you pause the script execution in the console and hover over this.move within the Ball or Player function, you'll notice that it is actually referencing:

function move() {
    player.move();
    ball.move();
}

This means that each time this.move is called inside the Player or Ball, it results in two additional calls to player.move() and ball.move().

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 Zorro table is filled with items of various types, although unfortunately, the Intellisense is not as accurate as it

Imagine a scenario where you have a basic table set up: <nz-table #table [nzData]="users"> <thead> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> </tr> ...

What is the best way to tally a score after analyzing two spans in Javascript?

I have 3 spans where 2 contain an alphabet each. The third span is left blank for the result of comparing the first 2 spans. I need to display the result in the last span, showing a value of 1 if the two spans contain the same alphabet. Can anyone sugges ...

Maximizing performance: optimizing Javascript usage in .net Web Application

After completing a web application using C#, ASP, and some javascript, my main page is cluttered with a mix of javascript/jQuery at the bottom. I have several ajax calls to web methods in this mess. Is there a way to organize this javascript into multipl ...

Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error: XML ...

SortTable - Refresh Dropdown Filter in Header After Adding Row to Table

My tablesorter table initially displays two entries in the "License" Filter. https://i.sstatic.net/4XODb.png If I dynamically add a row, the table now looks like this: https://i.sstatic.net/vMMYc.png I have attempted to update the table using the follow ...

What is the best approach for retrieving a User from my Angular front-end service?

INQUIRY: I'm attempting to retrieve the details of the currently logged in user in my Angular 2 frontend service with the following code: UserModel.findById(userID, function (err, user) { It appears that this behavior is achievable from the browse ...

Establish individual states for every dynamically created component using the same handler function

I have a component in React built with Material UI, where the child component (Paper) is dynamically generated depending on the number of items in an array. The challenge I'm facing is changing the elevation property of the Paper component when it&ap ...

Confusion surrounding the Javascript object prototype (utilizing require.js and three.js)

I'm feeling a bit confused about my understanding of Objects, prototypes, require.js and three.js. Let me illustrate with an example: In Summary: The instance "wee" is derived from "Wee," which acts as a wrapper or monkey patch for THREE... Shouldn& ...

Implementing JavaScript for showcasing weights

I've encountered a JavaScript function that modifies user preferences for weight units, allowing them to choose between metric and imperial measurements. When displaying weights on my page, I typically present them as follows: This is a brief explan ...

I recently implemented a delete function in my code that successfully removes a row, but now I am looking to also delete the corresponding data from localStorage in JavaScript

I have successfully implemented a delete function in JavaScript that deletes rows, but I also want to remove the data from local storage. This way, when a user reloads the page, the deleted row will not appear. The goal is to delete the data from local s ...

Ajax Multidimensional Array Response

Currently, I am attempting to retrieve a Multiarray response from an ajax Post JSON request. After numerous attempts, I am hopeful that I can get assistance here... JS AJAX RESPONSE var data = { "myid": "1234" }; $(".the-return").html(""); $.ajax({ ...

Creating Dynamic Web Design: Horizontal Scrolling Window and Adaptive HTML Content

After spending countless hours researching online, I am still unable to find a solution for responsive web design that maintains the aspect ratio of both the window and HTML body. Here are examples of what I'm looking for: original view, stretched le ...

Encountered an Angular SSR error stating "ReferenceError: Swiper is not defined"

When attempting to implement SSR (Server-Side Rendering) in a new project, everything runs smoothly and without issue. However, encountering an error arises when trying to integrate SSR into an existing project. https://i.sstatic.net/QOI6A.png ...

What is the best way to change the name of a property within an object

I need to update the names of properties in a nested object. { 0: {value: "can_view"}, 1: {value: "can_create"} } The desired output should be: { user_can: "can_view", user_view: "can_create" } ...

Keyframes and CSS Animation for Border Effects

I've been struggling to achieve a specific animation that I can't seem to get right. Despite searching online for solutions, none of them quite match the desired effect. What I'm looking for is a border animation that starts at the bottom l ...

Generate several different elements

Is it possible to use Vue.js to render a component multiple times based on a variable? For instance, I have a size variable set to 5 and I want to display the Widget component 5 times. Here is my current code snippet: Template : <template> &l ...

Favicon not appearing on Jekyll website

This is my first time working with Jekyll. I'm currently working on localhost and trying to set a favicon for the website. I generated the image.ico and added the code provided to my head.html file. The image appears in my _site folder, but it's ...

Excessive Spacing Below Picture

I am trying to position an image and a div directly beneath it, but I am encountering an issue with a visible margin between the two elements. You can view the code snippet here: http://jsfiddle.net/d3Mne/1/ Upon further investigation, I have noticed that ...

Build a React application using ES6 syntax to make local API requests

I'm really struggling to solve this problem, it seems like it should be simple but I just can't figure it out. My ES6 app created with create-react-app is set up with all the templates and layouts, but when trying to fetch data from an API to in ...

The challenge of incorporating mod_rewrite with CSS files

I am new to mod_rewrite. I have a page profiles.php?page=XXX and I tried to change its URL to something more friendly like /cars/XXX/ RewriteEngine on RewriteRule ^cars/([^/]+)/?$ profiles.php?page=$1 [L] The issue arises when including styles: <li ...