Timeout set to run indefinitely

Looking at the code snippet below, it seems to be running at a frame rate of 60 frames per second. If any button is clicked, the variable isjump will be set to true and the following code will start executing. The goal here is to exit the jump() function after 1 second. I have tried using setTimeout as shown below, but the lines inside the setTimeout are running indefinitely. Can someone please help?

My ultimate objective is to exit the jump function after 1 second.

function jump() {
    if (isjump) { 
        player.posx +=10;
        console.log("jumping"); //this line should stop after 1 second
        setTimeout(function () {
            isjump = false;
            console.log("stopped"); //however, this line keeps on running 
        }, 1000);
    }
}

I have also attempted using clearTimeout without success.

var timeoutHandle = window.setTimeout(function () {
    isjump = false;
    console.log("stopped");
    clearTimeout(timeoutHandle);
}, 500);

Edit: Just to clarify for those who may think the jump function is called continuously - yes, it is indeed called continuously. The game character position is updated for every frame.

Answer №1

After some trial and error, I finally came up with a solution for the problem I was facing. By adjusting the settimeout function to run only once inside a loop, I was able to resolve the issue.

var executed = true;
function leap() {
    if (canLeap) { 
        player.positionX += 10;
        console.log("leaping"); //this message stops displaying after 1 second
        if(executed)
        {
            setTimeout(function () {
                canLeap = false;
                console.log("finished leaping"); //however, this message keeps appearing
            }, 1000);
        }
        executed = false;
    }
}

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

Using a ternary condition within the ngClick directive

Trying to implement different functionalities based on the type of device. The setting tab is clickable, and in the desktop version, clicking should redirect to a default URL. However, on mobile devices, clicking the same link should open a modal window. ...

At times, AngularJs template tags fail to evaluate

Can anyone explain why the templating tag [[ opt.option ]] is not always evaluating to a value in this code snippet? <span ng-repeat="opt in options"> <button ng-click="button = [[ opt.option ]]" ng-class="{ active : button == [[ opt.option ]] ...

The regex string parameter in node.js is not functioning properly for matching groups

The String.prototype.replace() method documentation explains how to specify a function as a parameter. Specifying a string as a parameter The replacement string can contain special patterns for inserting matched substrings, preceding and following portion ...

Tips for implementing a button redirection to a different page using React

I am facing an issue with a component that includes a function onClick in its Class.propTypes: onClick: PropTypes.func Within another component, I have used this particular component multiple times to populate a page. Each instance of these components con ...

Storing the selected value from a dropdown box in PHP

Can anyone help me with echoing the $row['price'] based on the user's GPU selection? Your input is greatly appreciated! #adding more content to meet word count requirements. <div id="content"> <table border="1" style="width: ...

Transforming an HTML file into a Vue.js component

I'm working on a login.vue file and I need to incorporate styling along with the necessary js and css files. Unfortunately, I'm clueless about how to achieve this within the login.vue file. Below is a snippet from the html file: <!DOCTYPE ht ...

Determine if the input text field contains any text and store it in a variable using jQuery

I'm working on a form that includes radiobuttons and textfields. To keep track of the number of checked radiobuttons, I use this code: var $answeredRadiobuttons = $questions.find("input:radio:checked").length; But how do I store the number of textf ...

Dealing with a jQuery/JavaScript issue involving thumbnail images

I am facing an issue with smooth transitions between thumbnail images in HTML list tags. I have Jquery listeners set up for mouseenter and mouseleave events that update a parent image when a thumbnail is hovered over. The problem arises when scrolling fro ...

Convert a list into a hierarchical structure of nested objects

Working with angular, I aim to display a nested tree structure of folders in an HTML format like below: <div id="tree"> <ul> <li ng-repeat='folder in folderList' ng-include="'/templates/tree-renderer.html'" ...

Create a dropdown menu using a PDO query to populate the selectable options

I need to create a Select List that dynamically populates items/information from a Query. I understand the importance of updating the select list every time the database is updated, so JQuery is required for this task. Although I have limited experience wi ...

Transmit data to a modal using JSX mapping technique

When working with a map that renders multiple items, how can I efficiently pass parameters like the item's name and ID to a modal component? render(){ return( <div> <Modal isOpen={this.state.OpenDel ...

When no values are passed to props in Vue.js, set them to empty

So I have a discount interface set up like this: export interface Discount { id: number name: string type: string } In my Vue.js app, I am using it on my prop in the following way: export default class DiscountsEdit extends Vue { @Prop({ d ...

The function to refresh content is causing errors in the code

Creating a comment and replies form where the replies display underneath each comment. I've encountered an issue where I can post replies normally, but when attempting to delete a reply, I must refresh the page. After refreshing, I'm only able to ...

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...

Searching for the most recent entry from a related group within an HTML table using jQuery

I have a list of students in different classes that looks like this Class StudentName RollNo. Class X Sarah 1 Class Y David 2 Class Z Emily 3 Class W Adam 1 C ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

Testing a Vue.js/Node.js application using Websockets

I'm working on a Vue project (version 3.0.3) integrated with a Node.js server. Can you provide guidance on how to conduct unit testing for this setup? The application is a game that relies on web-sockets for communication. ...

Changing array indices in JavaScript by splicing elements

I'm experiencing a curious issue that seems to involve overwriting array indices after splicing, or at least that's what I suspect. This problem arises in a small game project built using phaser 2 - essentially, it's a multiplayer jumping ga ...

When attempting to pass data to another page by clicking on a row, the result is that the data appears to be empty

I have been using the MUI-Datatable component, which is able to navigate to the next page. However, when I try to view the data on the History page, nothing appears. How can I resolve this issue? Data transfer to another page: Even though I can see the d ...

Exporting a VueJS webpage to save as an HTML file on your computer

Scenario: I am working on a project where I need to provide users with the option to download a static export of a webpage that includes VueJS as a JavaScript framework. I attempted to export using filesaver.js and blob with the mimetype text/html, making ...