Flip the switch just one time

Hey there, I'm currently working on a JavaScript game and facing an issue. I want to execute a function when an if statement is true, but the function keeps running repeatedly. I need it to run only once.

This is my current code:

//JavaScript
setInterval(function () {
    var characterTop = parseInt(
      window.getComputedStyle(character).getPropertyValue("top")
    )
    var characterLeft = parseInt(
      window.getComputedStyle(character).getPropertyValue("left")
    )
  
    if (characterTop > 200 && characterLeft > 700) {
      
      document.getElementById("win").classList.toggle("active")
      
      {stopMoveLeft();} 
      {stopMoveRight();}
      {stopMoveDown();} 
      {stopMoveUp();}   
    }
}, 50);

/*CSS*/
#win {
    height: 100%;
    width: 100%;
    background-color: black;
    position: fixed;
    top: 600px;
    transition: all 500ms linear;

}

#win.active {
    top: 0px;
}
<!--HTML-->
<div id="win"></div>

Is there a way to keep checking the condition but ensure that the function executes only once?

Answer №1

Here is a suggestion for you:

let interval = setInterval(function () {
    let characterTop = parseInt(
      window.getComputedStyle(character).getPropertyValue('top')
    )
    let characterLeft = parseInt(
      window.getComputedStyle(character).getPropertyValue('left')
    )
  
    if (characterTop > 200 && characterLeft > 700) {
      
      document.getElementById('win').classList.toggle('active')
      
      stopMoveLeft(); 
      stopMoveRight();
      stopMoveDown(); 
      stopMoveUp();

      clearInterval(interval);
    }
}, 50);

Answer №2

To ensure the code has only run once, you can use a boolean variable

var executed = false;

//javascript code snippet
setInterval(function () {
    var characterTop = parseInt(
      window.getComputedStyle(character).getPropertyValue("top")
    )
    var characterLeft = parseInt(
      window.getComputedStyle(character).getPropertyValue("left")
    )

    if (characterTop > 200 && characterLeft > 700 && !executed) {
  
      executed = true;
      document.getElementById("win").classList.toggle("active")
  
      {stopMoveLeft();} 
      {stopMoveRight();}
      {stopMoveDown();} 
      {stopMoveUp();}   
    }
}, 50);

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

Issue: EPERM - Unable to perform action, scan directory 'C:/Users/ . . . /node_modules/react-native-gesture-handler/android/'

Every time I execute the command: npx react-native run-android An error message is displayed as follows: Error: EPERM: operation not permitted, scandir 'C:/Users/ . . . /node_modules/react-native-gesture-handler/android/... Even after running the C ...

Leverage the power of Meteor by incorporating templates to dynamically inject HTML based on an event

I am currently generating HTML using JQuery on an event. However, I believe a better approach would be to use templates in Meteor, especially if the HTML becomes more complex. Template.example.onRendered(function() { paper.on({ 'cell:mous ...

Converting a timestamp to a date format within AngularJS interpolation

Is there a way to send a timestamp, such as 1519357500, to HTML and then convert it into a date format while using interpolation? I attempted the following approach but unfortunately it did not work: {{moment($ctrl.myTimestamp).format('MMMM Do YYYY, ...

How can one retrieve an element based on its attribute?

Below is a custom tag/directive that I am using: <tile class="ng-scope gridster-item" tilevalue="1" gridster-item="tile" row="0" col = "0" ng-repeat="tile in selectedTiles"> </tile> I'm trying to figure out how to set focus on this eleme ...

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Samsung devices exclusively showcase background in responsive design

I am encountering a major problem with my website design, specifically with its compatibility on mobile devices. To ensure its responsiveness, I have tested the design on my iPhone, iPad, and Windows Phone. Unfortunately, since I lack an Android device, I ...

Instructions for creating a select box with checkboxes:

I am currently working on incorporating a Selectbox that includes checkboxes within the selectbox itself, similar to the image shown below. However, I am encountering an issue where clicking on the select box does not open the checkboxes from another div. ...

Having trouble deleting a Repeatable Job from the Bull queue in Node.js

Upon attempting to utilize the removeRepeatableByKey method, I encountered an error stating that removeRepeatableByKey is not a function. Specifically, it mentioned that queue_1.taskQueue.removeRepeatableByKey is not a function. Furthermore, I am facing d ...

Creating chained fetch API calls with dependencies in Next.js

I am a novice who is delving into the world of API calls. My goal is to utilize a bible api to retrieve all books, followed by making another call to the same api with a specific book number in order to fetch all chapters for that particular book. After ...

Guide on implementing gradient animation effects in a React component

How can I implement gradient animation effects like this example in a React component using inline CSS? I need to utilize the CSS-based gradient animation effects shown below directly within the React component. Are there any specific packages available ...

What is the most effective method for incorporating Header and Footer in PHP?

What is the most effective way to create a header.php file for including header files on a page? Is it better to include this HTML section in the header.php file so it appears on every page? <!DOCTYPE html> <html lang="en"> <hea ...

Encountering issues when attempting to store images with node.js

Currently, I am attempting to obtain an image from wikimedia with the following link: upload.wikimedia.org/wikipedia/commons/thumb/e/e3/AybükeArslan_(3).JPG/220px-AybükeArslan_(3).JPG Unfortunately, when using node.js to retrieve the image, the wikimed ...

Searching for "unique elements" using AngularJS ng-repeat

I am trying to organize a list by category, but the challenge is that each category input is customized and can be added by any user in the list. My initial attempt involved using ng-repeat to filter out duplicate values (as seen in the code snippet uniqu ...

Styling a Kendo Dropdownlist with JavaScript

Incorporating Jquery Kendo Dropdownlist to showcase information in a list has been quite beneficial. My current objective is to introduce the mentioned styles (.k-list-container and .k-list-scroller) into the Dropdownlist via JavaScript. Moreover, I aim t ...

Chrome debug function named "Backbone" triggered

Backbone provides the capability to activate functions in other classes by utilizing Backbone.Events effectively. a.js MyApp.vent.on("some:trigger", function(){ // ... }); b.js function test(){ doSomething(); MyApp.vent.trigger("some:trig ...

Place the Javascript pop-up in the center of the screen

Hey there! I was able to create a popup on my screen but it's currently positioned in the center of the page instead of the screen itself. Is there a way for me to make sure it appears in the center of the screen and not just the page? I'm usin ...

Converting a nested array of children into a string within a multidimensional array

I am currently in the process of updating a single value (ElementStatus) within the multidimensional JSON file shown below. BuildingID: 1521 BuildingName: "PEN LLOYD BUILDING" BuildingNumber: "A" ElementList: Array(15) 0: {ElementID: 114, SurveyTypeID: 3, ...

Concealing elements with a radio button selector

On my website, I'm utilizing PHP to manage contact/subscribe functionality. The form is straightforward with two radio buttons allowing the user to choose between "subscribe" or "contact." If the user selects "contact," I want an additional "Message" ...

CSS - vertical and horizontal lines vary in thickness depending on the design

I am working on creating a grid that is automatically generated in my Angular 2 application. Currently, it consists of 1px wide divs as vertical lines and 1px high divs as horizontal lines. However, there seems to be an issue with inconsistent thickness be ...

Unable to properly execute object calls with promises

I was facing a challenge with my code where I wanted to return two values in my promise chain, but was only able to call one of them successfully. Here is the section of my code causing the issue: app.get('/projects', (req, res) => { practic ...