Automatically closing conditional statement/loop

I'm experiencing an issue with the following if condition:

function turnLedOn1(evt) {
    led.on();
    var executed = false;
    if (!executed) {
        executed = true;
        checkin1 = timestamp;
        alert('checkin1');
    }
}

Despite the intended behavior of only executing the if loop once, I am receiving multiple alerts (around 15) before it stops. Any suggestions on why this might be happening?

Answer №1

To optimize your code, it is recommended to move the declaration of var executed = false; outside the function closure.

var executed = false;
function turnLedOn1(evt) {
    led.on();
    if (!executed) {
        executed = true;
        checkin1 = timestamp;
        alert('checkin1');
    }
}

Declaring a variable within a function restricts its access only within that specific 'closure'. Each time the function runs, the variable gets reset as it is reinitialized with var ... = false;. Learn more about closures here.

Answer №2

Setting executed as false and then verifying if it is actually false - quite the paradox, isn't it? Perhaps keeping var executed = false global outside the function might do the trick.

var executed = false;
if (!executed) {
    ...
}

Warm regards,

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

Nuxt and Webpack error: Failed to parse module - Unexpected character (1:0)

https://i.sstatic.net/ope8z.png I am working on a Vue carousel component and my goal is to dynamically generate a list of .png files from the static folder. I have followed instructions from here and also from here. Below is an excerpt from my component: ...

Top recommendation: Utilizing Typescript to allow a customer to enhance an application using their own tailored code

Our application framework is built on Angular 9, providing customers the ability to customize applications with different fields and layouts. This functionality works smoothly. However, we now face a situation where a customer wants to incorporate special ...

Initially, the 'display none' CSS command may not take effect the first time it is used

I am currently working on a slideshow application using jquery.transit. My goal is to hide a photo after its display animation by setting the properties of display, transform, and translate to 'none' value. Although the slideshow application work ...

Dealing with Javascript Array/Serialization in C# (.NET)

I have implemented tableDnD to rearrange table rows and then serialized them using the function "$.tableDnD.serialize()". Now, I need to pass this serialized data to C# for further processing. What is the most effective way to do this? Below is a sample ...

Is it possible to transfer the style object from PaperProps to makeStyles in Material UI?

I am working with a Material UI Menu component and attempting to customize its border. Currently, I am only able to achieve this customization by using PaperProps inline on the Menu element. However, I already have a makeStyles object defined. Is there a ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

Is it not possible to update the innerHTML stored in a variable in real-time?

I am attempting to link a div's text with a variable that changes its value based on different button clicks (using plain JavaScript), but I am struggling to update the inner HTML dynamically. It only displays the initial value set on page load. What ...

Executing specific rendering procedures based on conditions for mapped data - React

When I map data in the returned render, can I then perform a conditional check on that mapped data? export default function App() { const prod = [ {'name': '1'}, {'name': '2'}, {'name': ' ...

Having trouble installing gatsby-plugin-transition-link using npm

https://i.stack.imgur.com/DyZxQ.png I'm facing some issues while trying to install gatsby-plugin-transition-link using npm. No matter what solutions I've attempted, the errors persist. Can anyone provide insight into what might be causing this p ...

Obtaining data from JSON arrays

My current challenge involves extracting data from the following link: and storing it in my database. However, I am encountering difficulties with manipulating the array in order to retrieve the last unix datetime. Despite multiple attempts to extract th ...

VueJS modal displaying data acts strangely

While using vueJS and Laravel, I encountered an issue with my modal losing its shape when I tried to display data in it. Even duplicate forms failed to show the data correctly. This occurred when I clicked on a button to open the modal and show the data. ...

dissecting mongo queries using nodes

I am thinking about organizing my mongo db queries into a separate js file to make it easier to reuse the code. I have tried the format below but it doesn't seem to work. Does anyone have any suggestions on how I could accomplish this? queries.js va ...

Is it possible to simultaneously run multiple functions with event listeners on a canvas?

I'm attempting to create a canvas function that displays the real-time mouse cursor location within the canvas and, upon clicking, should draw a circle. I came across this code snippet that reveals the x and y coordinates of the mouse: document.addEve ...

Is there a way to hide an image once my scrollable div has reached a specific height?

I'm currently working on a project that involves a scrollable div with arrows above and below. My goal is to have the arrow above only appear after the div has reached a certain height. Below is the code I've been using... $("#scrolldivup").hid ...

What is the solution to the error "modal is not defined" in Vue.js?

Hey guys, I need some help with an error that popped up: [Vue warn]: Error in v-on handler: "TypeError: $(...).modal is not a function". The issue is with the modal function Below is the code snippet from my welcome.blade.php: <body> &l ...

Clicking on Bootstrap Select Does Not Trigger Dropdown Opening

Currently, I am working on generating a dynamic set of bootstrap-select widgets that include a dropdown. My main challenge lies in preventing the select from closing the dropdown, which requires me to use 'event.stopPropagation()' on the dropdown ...

Issues with the functionality of the sliding menu in Angular are being encountered when trying to use $

Challenge I am facing an issue with a slider menu feature that I integrated into a mobile application for navigation purposes. The menu is functioning properly - it displays, allows flicking of the initial links, and can be closed by pushing the backdrop. ...

Transmit data to PHP via Ajax without needing to redirect

Struggling to figure out how to send an image from ajax to PHP after uploading it in a form? Here is the ajax call you can take a look at: var dataString = 'city='+ city_push + '&venue=' + venue_push + '&title=' + ti ...

The function `open` is not a valid prop for the `Dialog` component

Upon clicking an icon, a dialog box containing a form should appear for either adding a tab or deleting a specific tab. I have utilized reactjs, redux, and material-ui for the components. While I am able to display the dialog box when the icon is clicked, ...

Create a new feature in React JS that allows users to add a component to

I'm having trouble figuring out how to create a function that loads data (from a local json) into a li element, and then adds a new component to the clicked li upon click. Here's an example of what I'm trying to achieve: <ul> < ...