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

Timer Tool: JavaScript Countdown Application

I am currently working on a JavaScript countdown timer, but I need help with setting it to only run for 48 hours every time the page is submitted. Right now, when I enter a time, the timer counts down to that specified time. Can someone please assist me ...

"Encountering a 404 error while attempting to forward to an HTML

I've been encountering an issue while trying to transition from a JSX page to an HTML page. Every time I attempt to do so, I receive a 404 error stating that the page doesn't exist. It's puzzling because it is clearly present in my files and ...

Button from Bootstrap extends beyond the page on mobile devices

I am facing an issue with my button. It looks great on desktop, but when I switch to the mobile version, it goes beyond the screen width like in the image below: 1) How can I prevent this from happening with the code provided in my bootply? 2) Also, how ...

Perform an AJAX request within a condition prior to executing the subsequent AJAX request

Within my database, I have two tables. When the submit button is pressed, I aim to insert a new trader into the trader table and retrieve the ID using laravel 5.2 by utilizing post ajax under certain conditions. Then, execute another post ajax for invoic ...

The tab component is failing to load due to an issue with the Bootstrap tab

I've created a page displaying different locations with two tabs - one for Google Maps and another for weather. For example, take a look at this location: The issue I'm facing is that when switching between the tabs, they don't load fully. ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

Creating a Unique CSS Grid Border with Custom Images

I have a client project using nextjs and the design calls for a component with a custom border on a responsive CSS grid. I've successfully created the CSS grid with all the necessary content, but I'm struggling to add the required border as per t ...

What strategies can be implemented to maximize the effectiveness of Office ribbon commands within an AngularJS application?

Currently, I have developed an Office add-in using AngularJS (version 1.4) and ASP.NET MVC 4.5. The Angular controller and service JS files contain a significant amount of functionality that has already been implemented. Lately, I have been exploring the ...

AngularJS factory architecture for multiple functions

It's not the exact data I'm using in my project, but I'm simplifying it for demonstration purposes. In my AngularJS app, I have a factory like this: myApp.factory('inputinfo', function () { var self = { test: function (in) { ...

What could be causing the flex item to be wider than its container?

One issue that can arise when utilizing flexbox is the scenario where, as demonstrated below, the content exceeds the width of the viewport causing the flexbox items to become wider than their container. What are the factors contributing to this situat ...

Incorrect pathing in express.js

I've encountered an issue with my filter while attempting to redirect packages using two express.js routes: app.get('/billdetails/:year/:month/:phoneId', function (req, res, next) { var db = req.db; var year = req.params.year; v ...

What is the method for obtaining distinct hover-over values for individual items within a dropdown menu?

If utilizing angular2-multiselect-drop down, what is the correct method to obtain distinct hover over values for individual items in the drop down? When dealing with standard HTML, you can directly access each element of the drop down list if it's ha ...

I possess a button that decreases the value of a number in the database when pressed. I desire for this action to occur repeatedly without fail

I have a button that, when pressed, decreases a number in my database by one. I want this action to decrement the number each time it is clicked. Code in HTML and PHP <form method="post"> <div><?php $username = "root" ...

Issue with material table not showing data

Problem I've been working on integrating a material design table into my project, but I'm running into an issue where the data isn't showing up. I followed the example provided here but all I see is a single vertical line on the page: Upon ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

Modifying background with JavaScript and AJAX技术

I currently have a table structured like the following; <table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0"> <tr> <td id="aaa">&nbsp;</td> ... Using jQuery's ajax functi ...

getting v-model value updated when clicking button

How can I update the value of v-model DataJournals.Description in a looping data when a button is clicked? This is what I have attempted: template <tr v-for="(DataJournals, index) in DataJournal" :key="DataJournals.value"> <td> & ...

What are some clever ways to outsmart bootstrap rows?

Trying to find a way to work around Bootstrap rows. I have multiple col-..-.. items that I need to fit into one row, but modifying 8 complex .js files is not an option for me - and they refer to the children of the div I used as a bootstrap row. HTML manip ...

Search the table for checked boxes and textboxes that are not empty

Could you suggest alternative ways to express the following scenario? I have a table with 3 rows. Each row contains a column with 3 checkboxes and another column with just a text box. I would like it so that when the values are retrieved from the database ...

Creating personalized hooks that rely on React query requests

Utilizing a series of custom hooks, I am able to fetch data and perform various calculations based on that data. One particular hook calculates the total amount that should be set aside monthly for future expenses, using the output from previous data-fetch ...