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

Tips for enabling item draggability following AJAX filtering operations

I have a draggable list of names that can be filtered using checkboxes. When a checkbox is checked, an ajax call is made to filter the names. The list is displayed in an accordion format as shown below: <div id="myAccordion"> <?ph ...

Can one utilize Javascript to write in plain text format?

Currently, using JavaScript I have a plain text containing data that is displayed within my form tags. Everything is functioning correctly, but now I need to update the values inside the code of my form tags in order for the changes to also be reflected in ...

Performing simultaneous AJAX requests in Javascript and jQuery

function makeCall(file, handlerFile, sendMethod, formData) { //console.log(instance.files); $.ajax({ url: handlerFile, type: sendMethod, xhr: function() { // Custom XMLHttpRequest var xhr = $.ajaxSettings.xhr() ...

Execute the function if the text or value begins with a certain character

I'm trying to determine whether the text within a span starts with the letter "x" and then execute a function. I've come across using "^" in strings for this purpose, but am having trouble implementing it to check the text... <span>xfoo&l ...

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Is there a way to dynamically expand and collapse all table rows, with the latest row always remaining visible, using pure JavaScript?

I have a form input field where I enter data. The entered data is then displayed in a table as a new row, with the most recent entry at the top. What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over ...

Fabric JS i-text cursor malfunctioning when loading JSON data

When I initially create a fabricjs i-text object in a new window, the cursor works perfectly. However, upon loading a saved JSON file, the cursor no longer functions as expected. I am utilizing the league_gothic font. Please refer to the image below showi ...

Looping through a dynamic array in Vue.js

I am working with two arrays: days:[0,1,2,3,4,5,6] and wdays:[2,3,6] My goal is to iterate through both arrays and display the output as follows: 0 : not present 1 : not present 2 : present 3 : present 4 : not present etc... The implementation should be ...

Customize your click event with conditional styling in React

When the onClick event is triggered, I am attempting to modify a class by calling my function. It appears that the function is successfully executed, however, the class does not update in the render output. Below is the code snippet: import React from &ap ...

.mouseleave() triggers when exiting a designated boundary area

I'm attempting to implement a roll-up feature for a div when the mouse is over another div. The issue I'm facing is that the roll-up div closes even if the mouse just exits through the bottom border. Is there a way to achieve this using JavaScrip ...

List application now includes the capability of adding three items in one go, rather than just one

Furthermore, when the script is placed in the same file as the html, it results in the addition of two items simultaneously instead of three. var itemNum = 1; $("document").ready(function() { $("#addCL").click(function() { var itemId ...

React State-Driven Conditional Rendering

When selecting both the "Home Team" and "Away Team" options from two dropdowns, I need to display data for both teams in charts. You can view the prototype on codepen. Currently, I am only able to show one Line Component with a dataKey. How can I modify ...

A New Approach to Initializing Web Pages in ASP.NET (with a Surprising Twist)

Well, I've encountered quite the puzzling issue with a project I'm working on (it could even make it to the Daily WTF), and I'm hoping for some help in finding a solution. (Apologies in advance for the lengthy explanation...) About a month ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

using http to handle a 404 error

This specific function is designed to fetch data under normal circumstances and to return a value of 0 in the event of a 404 error. function retrieveData(url) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); ...

The value of a variable decreases upon being utilized in an Ajax API call

My tempid variable seems to lose some of its values when passed into the second API call. Despite logging the variable to console (console.log(tempid)) where it appears fine, once placed in the API call it only retains some of its value. I'm uncertain ...

getting data from JavaScript function by making an asynchronous request to RESTful API

My current challenge involves calling a JavaScript method that utilizes AJAX to access a REST service and then return the response to the original call. While this may seem straightforward, I have scoured Stack Overflow for answers but haven't found a ...

Actions for jQuery's mouseenter and mouseleave events

I've implemented a jQuery script that controls the visibility of elements based on mouse events: $("#divid").mouseenter(function() { $('#divid').show(1000); }).mouseleave(function() { $('#divid').hide(1000); }); $("#hldiv" ...

What is the best way to align the 'Typography' component in the center?

Attempting to center it using flexbox with justify-content did not yield the desired result. I also tried replacing the Typography component with a div tag, but still no success. import {AppBar,Zoom,Toolbar,Typography,CssBaseline,useScrollTrigger,Fab,ma ...