Continue executing code until the Button is clicked once more

I was learning some new concepts and had a question that I couldn't find an answer to online.

So, here's the button I have:

<button onClick={toggle} className="common-btn">{buttonText}</button>

I want this button to control the duration of a section of code being executed. In the toggle method, I update the state successfully. However, when I tried using a while loop to break out of the code execution like this:

...
setRunning(!running)
if(running){
    while(running) 
    {
      console.log("Running")
    }
}

... 

The problem is that it never breaks out of the while loop. Even if the state is false, the original while loop continues to run. Does anyone have any insights on how to approach this differently?

Answer №1

<button onClick={() =>toggle() } className="common-btn">{buttonText}</button>
setRunning(!running)
if(running){
     While(running) {
      console.log("Running")
      } 
}else{
 console.log("Not Running) 
} 

Have you ever considered writing in this style?

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

Activate the toggle menu

Hi there! I'm currently working on a menu and I want the clicked item to become active, switching the active state to another item when clicked. However, my current implementation is not working as expected. Any assistance would be greatly appreciated ...

Encountering a 404 Error while using my Next.js 13 API Route

I recently forked a project and attempted to set up an API Endpoint for my CRUD operations with a database. However, I encountered difficulties in accessing my endpoint. Even with a test on a dummy API https://jsonplaceholder.typicode.com/todos, I still re ...

Troubleshooting: Nextjs application deployment on cPanel resulting in a 500 internal server error

Having migrated my website from React to NextJS for SEO purposes, I am now facing difficulties deploying it. Despite following a tutorial (https://www.youtube.com/watch?v=lex3qZAf_Ok&t=1136s) and consulting the official NextJS documentation (https://ne ...

I need the language chosen using Lingui's Language Switcher (i18n) to persist throughout the app, even after a refresh

I have been experimenting with Lingui for internationalization (i18n) in my app. I followed the documentation and tutorial to create a language switcher, but I am unsure how to set it up so that the selected language persists throughout the app even after ...

The recently added item in nestedSortable remains stationary and does not shift positions

const menu = $("ol.menu").nestedSortable({ handle: '.move', items: 'li', placeholder: 'placeholder', opacity: 0.7, toleranceElement: '> i', c ...

jquery mouse event does not register on touch-based devices

I have a mouse move event set up to scroll a div. However, when I try to access the functionality using a tab it does not work. How can I integrate this functionality onto a touch device? $(document).ready(function(){ $('#tim').on('mous ...

Tips for updating the checkbox state while iterating through the state data

In my component, I have the ability to select multiple checkboxes. When a checkbox is selected, a corresponding chip is generated to visually represent the selection. Each chip has a remove handler that should unselect the checkbox it represents. However, ...

Updating JSON data in real time using JavaScript by manipulating MySQL database entries

My database has a mysql structure consisting of the columns ID, NAME, and TYPE. The data is then converted into a JSON format as shown below: [ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwick", type: "comedy"}, { ...

Utilizing the nested combination of map and filter functions

Struggling to grasp the concept of functional programming in JavaScript, my aim is to extract object boxart items with width=150 and height=200. Console.log(arr) the output shows [ [ [ [Object] ], [ [Object] ] ], [ [ [Object] ], [ [Object] ] ] ] I&apos ...

I am seeking assistance in troubleshooting this javascript code. Can someone please help me identify the issue?

function validateCredentials() { var username = document.forms["myForm"]["name"].value; var admin = "admin"; var user = "user"; var master = "master"; if (username == "&qu ...

Filling HTML5 Datepicker Using Information from a Model

Currently, I am in the process of developing a basic scheduling application for a project. To simplify the task of selecting start and end times/dates for our events, we have included a simple DateTime picker in the source code: <input type="datetime-l ...

Focused Filtering in DataGrid Pagination

Seeking to adjust the font size of numerical values (10, 25, and 50 as shown in the screenshot below) within rows per page selection within a pagination section of a DataGrid component. https://i.sstatic.net/PnIDa.png After inspecting each number, it was ...

Looking for a way to perform a component query on a grid?

Is there a way to query a grid in an extension window that does not have an id or itemId associated with it? I know how to do it with an id, but is there a way to do it without one? var yourGrid = Ext.ComponentQuery.query('yourGridID')[0]; ...

Safari doesn't properly display the noOfLines property in the Chakra-UI text component

I'm facing an issue with the Chakra-UI Text component in a TypeScript Next.js app. The noOfLines property is not displaying properly in Safari, but it works fine in Chrome. Any tips on how to fix this? <Box pt={3} width={'100%'}> & ...

Retrieve the index of the currently selected item in the dropdown menu

Here is my current select setup: <select class="form-control" ng-change="filtro(selected)" ng-init="Catalogos[0]" ng-model="selected" ng-options="item.Nombre for item in Catalogos"></select> I am trying to retrieve the index value of the sele ...

The attention is consistently drawn to the link within the OffCanvas element

I had successfully created a script that automatically gives focus to a particular element in a popup div when the down key is pressed in a textbox. However, things took a turn when I introduced a sidebar navigation pane using a Bootstrap offcanvas compone ...

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...

Transforming an array of strings into a visual representation

Having an issue parsing a string array for Highcharts consumption. The chart renders when values are static, but not when passed as an array. I have validated the string being parsed here. The main issue appears to be with this specific line: //This work ...

Exploring Head-Linked/Off-center View in Three.js

I'm attempting to create a permanent head-coupled perspective without relying on the full headtrackr library. My head will remain stationary, but it will not be directly facing the screen. For those interested, I have a small demonstration available ...

The `Route` component is expecting a `function` for the `component` prop, but instead it received an `object`

For a while now, I've been grappling with an issue that seems to be unique to me. The problem lies within my component and container setup for the start screen rendering at the initial route. components/DifficultySelection.jsx import React from &apo ...