The JavaScript game's set interval function is failing to execute at consistent 10-second intervals

Trying to incorporate gravity into a circular object in an HTML, CSS, and JavaScript game. Here is the relevant JavaScript code section:

Check out the code on repl.it: https://repl.it/join/wukcvzow-iamapersonthing

The specific part of interest in this tutorial is at the 06.44-minute mark:

Reference video tutorial at: https://youtu.be/3SsYZDJdeXk

JavaScript:

var block = document.getElementById("block");
var hole = document.getElementById("hole");
//add this for the setInterval function
var character=document.getElementById("character");

hole.addEventListener('animationiteration',() => {
  var random = Math.random()*3;
  var top = (random*100)+150;
  hole.style.top=-(top) + "px";
});

//interval function runs every 10 milliseconds

setInterval(function(){
  var characterTop = 
  //this is the gravity function
  parseInt(window.getComputedStyle(character).getPropertyValue("top"));
  character.style.top=(characterTop+3)+"px";
  
  },10);

It seems like the issue might be related to this last segment:

},10);

Since the code doesn't show any syntax or other errors, it's challenging to troubleshoot further. I've also experimented with the CSS but couldn't pinpoint the root cause of the problem.

As per the tutorial, the "10" was suggested to be the refresh rate, but it doesn't seem to be the case. That number somehow affects the speed of the ball's downward movement. My goal is to have the entire animation (ball moving down) refresh every 10 seconds.

In summary, I want the pink ball (character element) to continuously descend every 10 seconds. Currently, it drops once and then falls off the screen. It only drops again when the "RUN" button is pressed.

The HTML code for this project:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>FlappyBird</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <div class="sky">
    <div class="ground">


    <div id="game">
      
     
      <div id="block"></div>
      <div id="hole"></div>
      <div id="character">
        
      </div>
</div>
    <script src="script.js"></script>
  </body>
</html>

And the CSS styles:

*{
  padding:0;
  margin:0;
  
}

#game{
  width:400px;
  height:500px;
  border: 1px solid greenyellow;
  margin:auto;
  overflow:hidden;
}


#character{
width:50px;
height:50px;
background-color:rgb(255, 0, 149);
position: absolute;
top:250px;
border-radius:50%;

}

#block{
  width:50px;
  height:500px;
  background-color:greenyellow;
  position: relative;
  left:400px;
  animation:block 2s infinite linear;
}

@keyframes block{
  0%{left:400px}
  100%{left:-50px}
}

#hole{
  width:50px;
  height:150px;
  background-color:white;
  position: relative;
  left:400px;
  top:-500px;
  animation:block 2s infinite linear;

}

/*

.sky{
  background-color:aqua;
  width:400px;
  height:500px;
  position: relative;
}

.ground{
  background-color:brown;
  width:400px;
  height:100px;
  position: relative;
  top:500px;
}
*/

Answer №1

Thank you for providing additional details about your question. I believe I now have a better understanding and can give you a proper answer. Your patience is appreciated.

It seems that you are referring to a specific aspect in the video where a GIF appears in the upper right corner. The GIF shows a ball moving downward and then snapping back to its original position, repeating the fall. If you are looking to replicate this effect, my answer should be helpful.

Your code is correct as it is. The demo shown in the tutorial is essentially your code in action. The perceived "refresh" of the ball in the video is due to editing, where the video looped back to the beginning after playing through. This created the impression of a reset, though it was just the video repeating. (You can notice changes in the browser window appearance and the cursor movement indicating editing.)

I hope this explanation clarifies things for you...


Below is my initial response before you provided further details on your question. (There was some confusion on both our parts.)


Here are a couple of points I'd like to address:

  1. The setInterval() function requires a function and an interval timer in milliseconds. The function provided will run at the specified interval. For example:
setInterval(() => {console.log("something")},15);

"something" will be logged every 15 milliseconds.

In one of your comments, you mentioned confusion about the "10" as the refresh rate. This number does control the speed of the downward motion of the ball. A smaller value for the interval results in a quicker downward movement as the function is executed more frequently.

Additionally, why choose to build a game using CSS-manipulated HTML elements instead of using the <canvas> element? Manipulating CSS for game development can be unreliable, slower, and more complex. Using <canvas> or a library like p5.js is generally more efficient and straightforward. Is there a specific reason for your current approach?

Answer №2

It seems like there's a problem with Repl.

setInterval(function(){
  const previewTop = window.getComputedStyle(character).getPropertyValue("top");
  const oldTop = parseInt(previewTop);

  console.log({ previewTop, oldTop })

  character.style.top = `${previewTop + 3}px`;  
},10);

Could you please try logging this to see the result?

Answer №3

Alright, I believe I understand your question.

Process:

Initially, the setInterval(function, time) function is utilized to update the position of the ball every 10ms, causing it to move 3 points downwards. While it may appear to impact the speed, it actually accelerates the rendering speed.

Resolution:

One possible solution is to monitor the intervals of rendering, so when the ball goes off-screen, you can reset its position using character.style.top = '250px' to return it to its original starting point.

JS

setInterval(function(){
  var characterTop = 
  parseInt(window.getComputedStyle(character).getPropertyValue("top"));
  character.style.top=(characterTop+3)+"px";
  if(character.offsetTop > game.offsetHeight){
    // Game over
    setTimeout(() => {
      // Reset the ball after 1s
      character.style.top= "250px";
    },1000)
  }else{
    
  }
  },10);

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

Jsonip.com is providing both internal and external IP addresses

I'm utilizing to retrieve the IP address of users. In some cases, it is returning both an internal and external IP as a string separated by commas. I am interested in only obtaining the external IP address. Can I assume a specific order for the retur ...

Need help styling a CSS for an iFrame on the same domain as my website?

After doing some research and browsing through Stack Overflow questions, I've discovered that even if you don't have access to the iFrame's stylesheet, you can still make edits as long as it resides in the same domain as your webpage where y ...

Button Hover Effect: Transition with Style

I am trying to implement a one-second transition from the default color scheme to the hover color for a Button element in Material UI. I am using the transitions.create(props, options) method as described in this article: https://medium.com/@octaviocoria/c ...

Adjust the initial slider according to the values displayed in the following four sliders

Having an issue updating the slider value in the first one based on selected values from four other sliders. The selected value should not exceed 50, which is the maximum value in the first slider. Link to Working Fiddle : Below is the HTML code : & ...

Change the JavaFX ToggleButton's color and revert back to its original color

Can you tell me what the default background and border color is for a toggle button? Here’s an example of code that changes the background color of a toggle button: i.toggle11.setOnAction(e->{ if(i.toggle11.isSelected()){ i.toggle ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

trim() function acting strangely

There seems to be an unexpected occurrence with the trim() function, as it is removing the á character. https://i.stack.imgur.com/whZBN.png This particular code snippet is typically used in various JavaScript projects without any issues. However, a clie ...

Tips for inserting a placeholder into a form input field

I am currently working on developing a form displayed in this fiddle. My goal is to fit an entire placeholder text into the form. Here is the HTML I've used to create a compact input form: <div class="container text-center "> <div class= ...

Is it possible for me to pass a value through props that is not currently stored in the state?

Within the realm of Reactjs, imagine a scenario where there exists a <Parent> component containing state and a variable named foo, which is either 'global' or local to Parent. The question arises: Can we pass foo as props using <Child v ...

Location-based services: Updating the position of a Google Maps marker without refreshing the entire map interface

How can I update only the marker on a map when the device is in motion or has increased accuracy? I want to reload the map when the position changes, but only move the marker. Below is the code snippet that I currently have: if (navigator.geolocation) { ...

Is it possible to integrate applications developed using (JS, Node.js, Express, and MongoDB) into a Wordpress site?

After successfully building projects using JavaScript, Node.js, Express and MongoDB, I am now looking to incorporate them into my existing WordPress website. Is it possible to integrate these projects into WordPress, or would it be better to create a sep ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Encircle a circle within the Progress Tracker

Is there a way to create a ring around the circle in this progress tracker, similar to the image shown here? The progress tracker is based on You can view an example here. The CSS approach used was: .progress-step.is-active .progress-marker { backgrou ...

What is the best way to display each value from the array arr, containing strings, on separate lines?

Can you complete the function below to display each value in the array 'arr' on separate lines? <!DOCTYPE html> <html> <head> <title> ...

Dependency of multiple objects in Webgl three.js

I'm struggling with object dependencies and need help. I want to create a setup where one object is dependent on two other objects. Essentially, when I modify the position of one parent object (like changing the y-Position), the dependent object (chil ...

Issues with utilizing Jquery datepicker within a Vue.js component's v-for loop in Laravel

I am facing an issue with the Jquery date picker inside a v-for loop in my vue.js component. The date picker works fine outside of the loop, but inside the loop it does not behave as expected. Here is a snippet of code where the date picker is working cor ...

Is it possible to display a div when hovering over it and have it remain visible until

How can I make the div ".socialIconsShow" fade in when hovering over ".socialIcons", and then fade out when hovering over ".socialIconsShow"? Is there a way to keep the icons visible even after leaving ".socialIcons"? <div class="socialNetworks"> ...

Visibility of the br tag is not detected

I need to keep one specific div visible on the page while hiding all other content. However, I am facing an issue where the <br> tag inside that div is not showing up. <div id='min320'>min 320px<br>screen width required</div ...

How can you condense an if/else statement in JavaScript into one line?

When searching the DOM using $(current_form).find('input').data('option'), the result can either be undefined or a string of options like 'x|y|z'. To handle this, I typically split the string by calling split('|') to ...

Which programming language or technology utilizes the syntax <%VARIABLE%> and in what context is it employed?

First things first, I want to clarify that I'm not a developer, so this might be a simple question. Despite my research indicating that ASP typically uses this syntax, it's important to note that it is not the case here. I am currently delving i ...