Prevent the laser from continuing its incrementation cycle in JavaScript

If you want to see a live demonstration, simply copy the code into Notepad++ and run it in Chrome as an .html file. I encountered some difficulties when trying to display a working example using Snippet or CodePen, so unfortunately, I couldn't provide direct links to those websites.

The question at hand is this: when the laser is fired once, it behaves exactly as intended by incrementing with lzxR++; until it reaches the border of the game arena. However, if the space bar is pressed while the laser is still in motion, the code attempts to display the laser in two places simultaneously which creates a choppy effect. How can this be avoided? Is there a way to stop the incrementation and fire a fresh new laser with just one press of the space bar, even if the previous laser was mid-increment?

Below is the provided code snippet:

<html>

<head>
    <style>
        /* CSS styles for the elements in the game */
    </style>

    <title>Portfolio</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <SCRIPT LANGUAGE="JavaScript" type="text/javascript">
        // JavaScript functions for controlling the game

    </SCRIPT>

</head>

<body>

<div id="blueCanvas">
    <div id="laser"></div>
    <div id="blueBall"></div>
</div>

<p id="pixelTrackerTop">Top position is 0</p>
<br>
<p id="pixelTrackerLeft">Left position is 0</p>

</body>

</html>

Answer №1

Resolved the issue by implementing a variable named "g" and increasing its value after firing the laser!

var g = 0;
function keyBoardInput() {
var i = event.keyCode;


  if (i == 32) {
  if (g < 1) {
  shootLaser();
  g++;
  };


  };

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

Limiting the length of numbers in Material UI

Is there a way to restrict user input to only numbers with a maximum length of 3 in Material UI? <TextField id="score" label="score" className={classes.textField} name="totalScore" margin="normal" defaultValue={score} /> We specifically ...

Is it possible to delay the loading of a page using location.href?

Trying to determine when a page has finished loading using location.href. Currently, my code is set up like this and I want certain events to occur once the page is fully loaded. I attempted using $.get but encountered issues with my existing implementatio ...

NextJS function utilizes its own references within React and automatically fetches data without the need for an import

I recently purchased this template and I'm trying to figure out which page the code snippet "{getLayout(<Component {...pageProps} />)}" is directed to during the initial load. It seems like it might be a global variable hidden somewher ...

Failure to deliver Server Side Events (SSE) to the client side

I'm currently utilizing the MEAN stack and facing challenges with receiving events from the server side. Despite using EventSource, I am unable to make it work as intended. Although the connection appears to be open, no messages are being received fr ...

Encountering a misleading 404 error message from Axios

There seems to be an issue with the axios query function, as it is querying the wrong URL just before sending the query. getShows : function(){ if( ! this.query ) return false; var getURL = this.makeUrlFromObject(this.query); console.log('getUR ...

Having trouble making the FileField optional in Django - need assistance troubleshooting the error

I am currently attempting to upload a file. The uploading process is functioning correctly. Here is my Models.py code: class I(models.Model): top = models.ForeignKey(T) imgfile = models.FileField(upload_to='static/Uploaded_Images', blan ...

Encountering difficulty in implementing two modals simultaneously on a single web page while utilizing the useDisclosure() hook in Ch

ChakraUI provides a custom hook called useDisclosure() which gives you access to isOpen, onClose , onOpen. const { isOpen, onOpen, onClose } = useDisclosure() You can use the onOpen function as an onClick handler for a button to open a modal. <Modal ...

Separate the navbar-brand and nav-items onto separate lines within the Bootstrap 4 navbar

I would like to arrange the navbar-brand and nav-items on separate rows. Put the navbar brand on the first row and the navigation items on the second row Existing code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="nav ...

React issue: parent state becoming unresponsive when updating during input onChange event

I am currently working on a large form that consists of at least 50 input fields. I have developed a function within the form component to store the input values in the form's state: PARENT FUNCTION saveToState(details) { const { company } = thi ...

Warning: Fastclick alerting about an ignored touchstart cancellation

Having an issue with a double popup situation where the second popup contains selectable fields. Below is the code snippet I am using to display the second popup: $("#select1").click(function(e) { e.stopPropagation(); var tmplData = { string:[& ...

I am interested in updating my website's navbar to switch from displaying "login" to "logout" once the user has logged in using

Facing an issue with my navbar logic - I need to switch it from "login" to "logout" when the user is already logged in. Utilizing Nodejs and Ejs templates for this web project, I am currently employing Level 1 Authentication. Initially focusing on the basi ...

Highcharts: generating numerous series utilizing JSON dataset

I am struggling to generate a chart with multiple series using JSON data. Although I have successfully created one with a single series, it doesn't look right and the legend is missing. I need guidance on how to rectify this issue. Currently, I only h ...

What is the best way to create dynamic transparency based on cursor position?

Is there a way to create an animation like the one on https://meetwalter.com, where the transparency changes with the cursor's position? I previously attempted a similar implementation using CSS, but it seems that the website accomplishes this effect ...

Utilize jQuery to retrieve data attributes and set them as CSS properties in a key-value format

Looking at the HTML below: <h4 data-padding-top="100" data-padding-left="0" data-text-align="left" data-color="#ffffff">Promotion Two</h4> I aim to use the data attributes as CSS styles for the H4 element. I have attempted to achieve this ...

HTML/CSS Pricing structure

As a designer, I am attempting to craft a pricing table with a unique pricing arrangement. Despite my efforts with HTML and CSS, I am struggling to position the "12x" below the "R$" and have both appear next to the price of "219." Here is the pricing layo ...

Alter the database field value in MongoDB without relying on req.body inputs

Is there a way to update a value from X post in my database without using a form in my front end app? I need to trigger the update through a button click instead. Typically, we use req.body to send data from a form. But how do I handle updating the value ...

Oops! The requested page "/api/auth/[...nextauth]" is missing the necessary "generateStaticParams()" function, thus making it incompatible with the "output: export" configuration

Currently, I am working on a Next.js project where I have successfully implemented user authentication using next-auth with the Google Provider. However, while attempting to build the project, an error is being thrown by the compiler stating: "Error: Page ...

Arranging JSON information based on category

I am currently populating an HTML table with data retrieved from a JSON file. It currently displays all the data in the order it appears in the JSON file, but I would like to organize it into different tables based on the "group" category in the file such ...

Extracting data from a JSON response and presenting it within a div element, using a weather API

Looking to parse json data in order to extract information from the json response, specifically the values of weather.main and weather.description and then display them inside a div. Below is the sample json response along with the accompanying JavaScript/ ...

Issue encountered with the carousel plugin while transitioning to a different page (utilizing Durandal)

I am currently working on a project using the Durandal SPA template, and I have integrated a carousel element into my page: var compositionComplete = function () { $('.testimonials-carousel').carousel({ namespace: "mr-rotato" // ...