What is the best way to modify the properties of an object as soon as a specific condition is satisfied

I'm currently working on enabling a button transition from .disabled = true to .disabled = false. My project involves creating a Yahtzee game clone for entertainment, where players need to select a score to keep after their third roll. Once that choice is made, the button should become unlocked allowing them to roll again. I attempted to achieve this but encountered crashes. My initial idea was to use a while statement to wait until a score is chosen. The variable ptsss keeps track of the number of scores entered.

if(rollcount == 3){
      while (ptsss * 3 < rollcount){
         document.getElementById("rollbutton").disabled = true;
         if (ptsss * 3 == rollcount){
            document.getElementById("rollbutton").disabled = false;
            break;
         }
      }
    }
    }

Answer №1

To improve the code, consider converting the while loop into a function that can enable or disable the roll button based on certain conditions. Here is an example:

function checkRollButton( rollcount, ptsss) {
  if(rollcount == 3) {
    document.getElementById("rollbutton").disabled = ptsss != 1;
  }
}

You can then use or embed the checkRollbutton function in event handlers that update values like rollcount and ptsss.


  • Note that ptsss should not be altered by other parts of the code while the while loop is running due to JavaScript's single-threaded nature.
  • I have made adjustments to how the roll button is enabled or disabled in line with the expected behavior, but please review it before implementation.

Answer №2

When it comes to JavaScript, loops function differently compared to other programming languages.

If the loop's condition remains constant within the loop, it will not change unless it occurs inside an asynchronous function.

Avoid using getElement repeatedly within a loop.

To replicate the functionality of a while loop in other languages, JavaScript utilizes an interval.

Therefore, an updated code snippet might resemble the following (without the initial if statement and with modifications to the nested if statement):

var roll=document.getElementById("rollbutton") // ensure this is executed after the element loads

var inter=setInterval(function(){
    if (ptsss * 3 == rollcount) {
        roll.disabled = false;
        clearInterval(inter);
        // Acts like 'break' in a while loop; you can resume the interval later
    }
    if (ptsss * 3 < rollcount){
       roll.disabled = true;
   }
}, 1000/30); // 30 FPS

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

Transition the background image color smoothly from left to right in a seamless and continuous movement

A switch button located in the top right corner can toggle between light and dark modes. The background features a zoomed-in image. Currently, the transition is as follows: From left to right when switched to dark mode From right to left when switched to ...

AngularJS is not showing the dropdown options as expected

I am facing an issue where the dropdown list options are not displaying, even though I am able to fetch the data in the controller but not in HTML. Here is the code snippet: In HTML <select name="nameSelect" id="nameSelect" ng-model="model.name"> ...

The eel feature results in no output

During my Python program development using the Eel module, I encountered an issue. The problem is that the eel.getImgSrc(path) function returns null when trying to retrieve image's byte data. Take a look at this example: -----web/main.js------ async ...

Updating an item stored locally

I am currently working on a web application that utilizes local storage. I have successfully implemented functionality to add and delete items, but I am facing an issue with editing items. Although items can be edited as expected, upon refreshing the page, ...

What is the best way to incorporate ng-pluralize into a loop and access the count value?

Is there a way to access the iterator in the count attribute when using ng-pluralize within a loop? <option ng-repeat="i in [1,2,3,4,5]" value="{{ i }}"> {{ i }} star<ng-pluralize count="i" when="{'1': '', 'other': ...

Using either AngularJS's simple .then method or the $q service to handle asynchronous requests

I'm trying to understand the distinction between AngularJS $q service and simply using .then() after an asynchronous request. For example, using .then(): function InboxService($http) { this.getEmails = function getEmails() { return $http.get(& ...

What exactly does the term "library" refer to in the context of jQuery, a JavaScript

I'm confused about the concept of a library - when it comes to jQuery, can it be described as a large file containing multiple plugins that are pre-made and ready for use? ...

Click on the event to save the document and print the HTML page

Is there a way to create an onclick event that saves the current HTML page as a document and then prints it? <html> <body> <div class="reportformat"> <div class="format1"> <table> <tr ...

ui-grid-draggable-rows mistakenly identifies my data as a simple string

After successfully setting up the ui-grid-draggable-rows functionality by following the provided instructions, I encountered an error while running the code snippet from the example here. The error message I received is as follows: TypeError: this.spli ...

The Angular filter is failing to display the category value

My issue lies in adding a filter to display categories, as my setCurrentCategory function is not showing any value but instead displaying 'undefined'. The goal is to show the category for each person. I'm using ng-click to pass to my functio ...

Issue: tanstack_react_query's useQuery function is not recognized

Error: (0 , tanstack_react_query__WEBPACK_IMPORTED_MODULE_3_.useQuery) is not a function While implementing data fetching in my Next.js project using @tanstack/react-query, I encountered the above error message. Below is the code snippet where the issue ...

Issue with the Animated Skill Bar not functioning properly when scrolling

I've been trying to implement an animated skill bar in my Portfolio using JQuery, but I'm facing some challenges. Despite following various tutorials, the code doesn't seem to work as expected. I've tried calculating section scroll posi ...

The file upload process did not return a successful response for Ajax

Recently delved into the world of Ajax and encountered a perplexing issue. Here is the dilemma: I successfully upload a .csv file to the server. However, after the upload "success" in the ajax call fails to trigger a response. Neither does complete or er ...

Remove movable element from react-dnd

I am working with react-dnd and I am trying to figure out how to remove a draggable object once it has been used. I modified the react-dnd multiple type example by adding a delete feature when an object is dropped. Here is the current behavior: 1. Drag a ...

What could be the reason for the undefined initial state in my vuex store?

I am facing an issue with vuex-typescript where the initial state is always undefined. However, it works fine when I reset the state and refresh the window. Below is my setup for a simple module: import Vue from "vue"; import Vuex from "vuex"; import { m ...

arranging a collection of images based on their values in increasing order

cardShop is a container with various images, each with its own unique ID and value attribute. These values consist of two numbers separated by a comma, such as 2000,500 or 1500,200. My goal is to sort these images in ascending order based on the first numb ...

Using Redux Form to set the default checked radio button in a form setting

I'm currently attempting to make a radio button default checked by using the code below: import { Field } from "redux-form"; <Field name={radio_name} component={renderField} type="radio" checked={true} value={val1} label="val1"/> <Field na ...

Having trouble receiving a Java Response through Ajax when using dataType: "jsonp", but it works when using dataType: "text"

I am having trouble retrieving the Callback response value in ajax with the provided code snippet $.ajax({ type: 'POST', jsonpCallback: 'jsonCallback', contentType: 'application/json', url: apiurl, dataTyp ...

Trigger event when the useRef element's height surpasses zero

I have a large list of photo thumbnails, and I need to ensure that one of the thumbnails scrolls into view when the list is loaded. The photos are generated using the map function, and the container div of one of the thumbnails will be assigned a ref. I ...

Examining the scroll-down feature button

I'm currently experimenting with a scroll down button on my website and I'm perplexed as to why it's not functioning properly. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" c ...