One issue with my Quiz app is that sometimes the correct and incorrect answer methods run concurrently, leading to occasional occurrences of this problem

One issue I encountered while developing a Quiz app is that sometimes the methods for correct and incorrect answers run simultaneously. This problem occurs sporadically.

I want to highlight that my code is functioning correctly. The only challenge I face is the occasional occurrence where the methods this._incorrect() and this._correct() execute at the same time.

'use strict';
/** Import */
import harryPotterName from './NamesArray.js';

/**Const */
const btnAll = document.querySelectorAll('.btn');
const divPicture = document.querySelector('.divPicture');
const scoreDOM = document.querySelector('.score');

class QuizzGame {
  /*settings */
  #randomNumArr = [
    [0, 1, 2, 3],
    [4, 5, 6, 7],
    [9, 10, 11, 8],
    [12, 13, 14, 15],
    [16, 17, 18, 19],
    [20, 21, 22, 23],
    [24, 25, 26, 27],
  ];

  #score = 5;

  constructor() {
    this.arr = this.#randomNumArr[this._rand()]; // array Destructuring
    this.randInArr = Math.floor(Math.random() * 4); // rand in arr [0,2,3,4] = rand [2]
    this.id = this.arr.at(this.randInArr); // Slice

    btnAll.forEach((btn, i) => {
      btn.setAttribute('data-id', this.arr[i]); // Set Attribute [data-id, i]
      btn.innerHTML = harryPotterName[this.arr[i]];
      btn.addEventListener('click', e => this._ButtonHandler(e));
    });

    this._init();
  }

  _rand() {
    return Math.floor(Math.random() * this.#randomNumArr.length);
  }

  _randInArr() {
    this.arr = this.#randomNumArr[this._rand()];
    this.randInArr = Math.floor(Math.random() * 4); // rand in arr [0,2,3,4] = rand [2]
    this.id = this.arr.at(this.randInArr); // Slice
  }

  _ButtonHandler(e) {
    console.log(+e.target.dataset.id, this.id);

    if (+e.target.dataset.id !== this.id || this.#score <= 0) this._incorrect(); // incorrect Answer
    if (+e.target.dataset.id === this.id && this.#score > 0) this._correct(); // correct Answer
  }

  _incorrect() {
    console.log('_incorrect');
    scoreDOM.textContent = this.#score <= 0 ? 'you lose' : --this.#score;

    this._randInArr();
    this._nextQuestion(); // next to the Question
    this._showImg(); // render img
  }

  _correct() {
    console.log('_correct');
    scoreDOM.textContent = ++this.#score;

    this._randInArr();
    this._nextQuestion(); // next to the Question
    this._showImg(); // render img
  }

  _nextQuestion() {
    btnAll.forEach((btn, i) => {
      btn.removeAttribute('data-id');
      btn.setAttribute('data-id', this.arr[i]); // Set Attribute [data-id, i]
      btn.innerHTML = harryPotterName[this.arr[i]];
    });
  }

  _showImg() {
    divPicture.innerHTML = `
      <img class="rounded mx-auto d-block" src="images/Players/${this.id}.jpg" />
    `;
  }

  _init() {
    scoreDOM.textContent = this.#score;
    this._showImg();
  }
}

new QuizzGame();

Answer №1

The issue lies in this part of the code. When an answer is marked as incorrect, it triggers the function this._incorrect(), which changes the value of this.id. Subsequently, another condition is evaluated where this.id has already been altered, potentially leading to a scenario where the answer passes as correct, even though it is actually incorrect.

  _ButtonHandler(e) {
    console.log(+e.target.dataset.id, this.id);

    if (+e.target.dataset.id !== this.id || this.#score <= 0) this._incorrect(); // incorrect Answer
    if (+e.target.dataset.id === this.id && this.#score > 0) this._correct(); // correct Answer
  }

To resolve this issue, it is recommended to create a local variable for this.id within your _ButtonHandler function. By doing so, even if this_incorrect() is invoked, it will not modify the original value of this.id. This way, the execution of your _ButtonHandler will not be influenced by unintended side effects.

_ButtonHandler(e) {
  let capturedId = this.id // <- HERE    
  console.log(+e.target.dataset.id, this.id);

  if (+e.target.dataset.id !== capturedId || this.#score <= 0) this._incorrect(); // incorrect Answer
  if (+e.target.dataset.id === capturedId  && this.#score > 0) this._correct(); // correct Answer
}

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

I'm encountering an error when trying to pass multiple parameters in an AJAX request

I am trying to pass three parameters to my ajax code. Here is the snippet of my code: $(document).ready(function () { SearchText(); }); function SearchText() { $("#txt712").autocomplete({ source: function (request, resp ...

Creating a Bottom-Up Menu in React Native: A Step-By-Step Guide

Need help figuring out how to create a menu that pops up from the bottom when a button is clicked. Any advice on where to start? If you have any guidance or insights, they would be highly appreciated. ...

Accessing data stored in XML or JSON files from a local server

I am currently working on loading a list of coordinates for a Google map from either an XML or JSON file, both of which are hosted in the same directory on my local test server. So far, I have used a hard-coded JSON object to load map coordinates for tes ...

Ways to launch the React Material date picker while hiding the date input field

I am working with the react material (MUI-X) date picker and my specific requirement is to have the date picker open on button click without displaying the date text field. I simply want to show the calendar and allow users to select a date. I have explore ...

Arranging serialized information from a tabular format and retrieving specific data

: I'm currently attempting to utilize an AJAX POST request to send data from a dynamic webpage that includes information gathered from a table form, a date selection box, and comment text input. The webpage is generated as a PHP file on a GET request ...

does not output any console log statements

I am attempting to showcase the values of checkboxes on the console, however, it is not working. <input type="checkbox" id="id_price" value="1" onclick="display_img()">Under £200<br> <input type="checkbox" id="id_pr ...

What is the best way to apply the addClass method to a list element

I've been searching for a solution to this issue for some time now, and while I believed my code was correct, it doesn't appear to be functioning as expected. HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js ...

Problem with Onsen UI navigation: It is not possible to provide a "ons-page" element to "ons-navigator" when attempting to navigate back to the initial page

Hi, I am having trouble with navigation using Onsen UI. Here is the structure of my app: start.html: This is the first page that appears and it contains a navigator. Clicking on the start button will open page1.html page1.html: Performs an action that op ...

Supplying information to my ejs template while redirecting

I am currently working on a feature that involves sending data from the login page to the home page when the user is redirected. This data will then be used in the home EJS file. Below is the code snippet I have implemented: module.exports = functio ...

Execute a Python script using an Ajax jQuery call

Recently, I encountered an issue when attempting to execute a python file via jQuery. To address this problem, I conducted research online and came across a specific code snippet designed to call and run a python script. Below is the AJAX code utilized fo ...

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

The ng-model in Angular is unable to capture the initial input value on load

I am currently using a window onload script to obtain longitude and latitude data and pass them to hidden input values. $(function() { window.onload = getLocation; var geo = navigator.geolocation; function getLocation() { if (geo) { geo ...

Interfacing with Ajax to dispatch information to a PHP script

Hello, I'm currently working on implementing Ajax in my web application. However, I've encountered a small issue. I'm attempting to check if a username has already been registered by controlling a form. The problem arises when my JavaScript ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

I'm struggling to solve a straightforward jQuery sliding issue

I am struggling to make text slide from right to left on my website. I want the text to appear only when the page loads or refreshes, and then slide off when a link is clicked, revealing new text. Can anyone help me figure this out? http://jsfiddle.net/XA ...

Which child node of the html tag represents the "text"?

In my quest for answers, I have searched extensively but to no avail: As we all know, when a web page is loaded in a browser, it generates a tree-like structure called the Document Object Model (DOM). This allows Javascript to manipulate the elements of t ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

The JavaScript function Date().timeIntervalSince1970 allows you to retrieve the time

For my React Native app, I currently set the date like this: new Date().getTime() For my Swift App, I use: Date().timeIntervalSince1970 Is there a JavaScript equivalent to Date().timeIntervalSince1970, or vice versa (as the data is stored in Firebase clo ...

Remove the image by clicking on the "X" icon located on the top right corner of the image

One of my tasks involves deleting an image by clicking on the "X" mark located at the top right corner of the image. To achieve this, I referred to this CSS fiddle http://jsfiddle.net/yHNEv/. Sample HTML code: <div class="img-wrap"> <span ng-c ...

What is the best way to implement JavaScript for loading and removing content based on button clicks on a webpage?

I'm in need of a vanilla JavaScript solution (I know JQuery options exist, but I want to stick to vanilla JS for now)? Currently, I am using a simple page as a testing ground for my ongoing project. The page consists of two buttons that load HTML pag ...