Stopping an endless loop in JavaScript by pressing a key on the keyboard can be a useful

I've been working on creating a JavaScript game and am currently tackling the challenge of implementing gravity. One crucial aspect I need to address is creating an infinite loop without causing the browser to crash. Is there a way for me to include a break statement that only triggers under specific conditions?

Below is the current loop I have:

for (i = 0; i < Infinity; i++) {
  if (moveY > 300) {
    moveY = moveY - i * 2 + 3;
    move(moveX, moveY);
  } else {
    i = 0;
  }
}

Answer №1

When it comes to creating a game loop in JavaScript, the key is to avoid an infinite loop and instead utilize requestAnimationFrame

const p = document.querySelector('#p');

function gameloop(time) {
  time *= 0.001;  // convert to seconds
  
  p.style.transform = `translate(${100 + Math.cos(time) * 100}px, ${100 + Math.sin(time) * 100}px)`;  

  requestAnimationFrame(gameloop);
}
requestAnimationFrame(gameloop);
html, body {
  height: 100%;
  margin: 0;
  overflow: hidden;
}
.sprite {
  position: absolute;
  left: 0;
  top: 0;
  background: red;
  color: white;
  border-radius: 1em;
  padding: 0.5em;
}
<div class="sprite" id="p">player</div>

To handle input, events such as keyboard events come in handy.

const p = document.querySelector('#p');
let x = 100;
let y = 100;
let dir = 0.2;
const vel = 100;  // 100 pixels per second
const turnSpeed = Math.PI;  // half a turn per second
const keys = [];

let previousTime = 0;
function gameloop(currentTime) {
  currentTime *= 0.001;  // convert to seconds
  deltaTime = currentTime - previousTime;
  previousTime = currentTime;
  
  if (keys[37]) dir -= turnSpeed * deltaTime;
  if (keys[39]) dir += turnSpeed * deltaTime;
  
  const dx = Math.cos(dir) * vel * deltaTime;
  const dy = Math.sin(dir) * vel * deltaTime;
  
  x = (x + dx + window.innerWidth) % window.innerWidth;
  y = (y + dy + window.innerHeight) % window.innerHeight;
  
  p.style.transform = `translate(${x}px, ${y}px) rotate(${dir}rad)`;  

  requestAnimationFrame(gameloop);
}
requestAnimationFrame(gameloop);

window.addEventListener('keydown', (e) => {
  keys[e.keyCode] = true;
});
window.addEventListener('keyup', (e) => {
  keys[e.keyCode] = false;
});
html, body {
  height: 100%;
  margin: 0;
  overflow: hidden;
}
.sprite {
  position: absolute;
  left: 0;
  top: 0;
  background: red;
  color: white;
  border-radius: 1em;
  padding: 0.5em;
}
<div class="sprite" id="p">player</div>
<div>click here then press &lt;- or -&gt;</div>

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

I am struggling to display an array of objects retrieved from the server in the UI using AngularJS

I am receiving an array of objects as a JSON from the server. When I try to access my service URI from HTML, I encounter the following array in my console: "angular.js:13920 Error: [$resource:badcfg] http://errors.angularjs.org/1.5.8/$resource/badcfg?p0= ...

Create a regular expression to identify and substitute incorrect HTML properties

It's a harsh reality that my regex skills are lacking. Upon revisiting an old project, I stumbled upon some code that definitely needs attention. Take a look: strDocument = strDocument.Replace("font size=""1""", "font size=0.2") strDocument = strDocu ...

Combine various choices into a select dropdown

I am facing an issue with an ajax call in codeigniter where the response always consists of two values: team_id1 and team_id2. Instead of displaying them as separate values like value="1" and value="2", I want to join them together as value="1:2". I have ...

Executing an Ajax call to trigger a NodeJS function that executes a bash script

I have created a bash script to generate a JSON file that needs to be parsed and sent to the client-side JavaScript for display. My goal is to achieve this without refreshing the page and without using jQuery. I attempted to use Axios but seem to be facing ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

Utilizing AJAX to upload a file and managing it through a Java servlet on the server side

I've been struggling with this particular issue for the past few days and haven't found any helpful resources elsewhere. I'm attempting to upload a file through an HTML form that includes other input fields: var formData = new FormData() ...

Leveraging conditional statements for dynamically computed Vue properties

In the Vue site I'm working on, there is a functional button that changes its state when clicked (from "pause" to "resume" and also changes colors). The button functionality itself works perfectly, but I am facing an issue in aligning it with another ...

Error: The combination of 0 and .... is invalid and cannot be used as a function

I am currently in the process of developing a next.js application using Material-ui. I have been attempting to integrate material-ui into my project. Following guidance from the official GitHub page, I have copied the _app.js , _document.js , theme.js fil ...

The HTML Style for implementing HighChart title text does not work when exporting files

I have inserted the <br/> and &nbsp; HTML tags into the HighChart titles. The style changes successfully appear in the chart view, but unfortunately, when exported as PNG or JPEG images, the text style fails to apply in the resulting images. To s ...

Exploring the Differences between Slim Framework's Currying and Dependency Injection

Frameworks like Angular allow for injecting services and controllers into each other, as shown in the code snippet below: App.controller('exampleController', function($scope, ajaxService){ ajaxService.getData().then(function(data) { ...

Unsuccessful translation of HTML symbol codes within a toggle function using jQuery

Is there a way to toggle between the symbols + and - using HTML entity codes &#43; and &#45;? I have attempted different solutions for toggling HTML content, but none seem to work correctly with these specific codes. It toggles once, but doesn&apo ...

The input box is not properly filled with the complete string using protractor sendKeys

[HTTP] --> POST /wd/hub/session/ffcd7072-9f96-45cb-a61d-ec53fc696b56/element/0.9513211246393813-32/value {"value":["1","0","0","0","1"],"text":"10001"} My JavaScript code snippet: this.zipcode = element(by.model('personalInfo.zipcode')); this ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

Using percentages for sizing and margins in CSS

Looking to create a visually appealing page that always fills the entire screen? Check out this code snippet that does just that: #posts{ width:100%; height:auto; background:#666; } .entry{ float:left; margin-left: 4%; margin-top:10 ...

What steps are required to insert additional tags into select2?

I've successfully retrieved the tags from my API, but I'm facing an issue with adding new tags. Here's the code snippet I've been using: $(function(){ var user_email = localStorage.getItem('email'); var api = ...

Synchronize numerous PouchDB databases with a single CouchDB database

After reading the PouchDB documentation, I learned that sync occurs between a local database and a remote CouchDB database. Currently, I am working on developing a native application that includes a unique local database for each user (multiple databases) ...

Retrieve the child element index of a specific element using jQuery

I am dealing with a group of 'DIV' elements, each containing a list of 'p' elements. Take a look at the example below: <div class="container"> <p>This is content 1</p> <p>This is content 2</p> ...

Why is it that when I refresh the page in Angular, my logged-in user is not being recognized? What could be causing this

I am developing a Single Page Application using the combination of Angular JS and Node JS. In my HTML file, I have defined two divs and based on certain conditions, I want to display one of them using ng-if. However, I noticed that the model value used in ...

Exploring ES6 classes in Java Script: accessing prototype properties

After searching extensively for an answer and coming up empty-handed, I decided to pose my question here. When creating an object constructor in JavaScript as shown below: function Car(speed){ this.speed = speed; this.position = 0; } Car.prototype.m ...

Utilizing JQuery Mobile to handle multiple forms on a single page and submitting each form uniquely by its ID using JQuery Post

After experimenting with assigning the same form ID to all forms on the page and also giving each form individual IDs with unique.submit functions, I encountered an issue where only the first form would work while the rest would redirect me back to the hom ...