Tips for displaying an alert in the upcoming event loop

I recently started learning VueJS and decided to create a practice game to strengthen my understanding of the framework.

http://jsfiddle.net/mzref4o0/1/

Within this game, the attack method is crucial in determining the winner:

attack: function(isSpecialAttack) {
        let youHurt = Math.floor(Math.random() * 10);
      let monsterHurt = Math.floor(Math.random() * 10);
      if (isSpecialAttack) {
        youHurt = Math.floor(Math.random() * (20 - 10 + 1)) + 10;
        monsterHurt = Math.floor(Math.random() * (20 - 10 + 1)) + 10;
      }
        this.you.bloodLevel -= youHurt;
      this.monster.bloodLevel -= monsterHurt;

      this.messages.push([
        {id: this.getRandomId, turn: 'you', msg: 'PLAYER HTIS MONSTER FOR ' + monsterHurt},
        {id: this.getRandomId, turn: 'monster', msg: 'MONSTER HTIS PLAYER FOR ' + youHurt}
      ])


      if (this.you.bloodLevel <= 0 || this.monster.bloodLevel <= 0) {
        if (this.you.bloodLevel <= 0) {
          alert('you lost');
        } else {
          alert('you won');
        }
      }
    },

The challenge I'm facing is that the alert message appears before the "attack" process completes, resulting in the blood bars dropping and the message being added after the alert is displayed. How can I ensure that the alert only appears once these actions are finished?

I suspect that this issue may be related to the event loop, but I'm not entirely sure.

Answer №1

The desired outcome may not be achievable using the alert function.

Using the alert method can cause code execution to be blocked, delaying any re-painting in the browser.

You can find a suggested solution in another stackoverflow post here.

I suggest utilizing more modern techniques such as vue-js modals.

Nevertheless, you can try using this block of code:

if (this.you.bloodLevel <= 0 || this.monster.bloodLevel <= 0) {
    if (this.you.bloodLevel <= 0) {
        setTimeout("alert('you lost');", 1);
    } else {
        setTimeout("alert('you won');", 1);
    }
}

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

VueJS Router error: The variable $route is undefined

Check out my component: const Vue = require("vue/dist/vue.js"); const qs = require("querystring"); module.exports = Vue.component("Page",function(resolve){ console.log(pageRoute); let id = pageRoute.params.id; fetch("/getPage.json",{ ...

How to create a dynamic rectangle using mouse movements in VUE with Konva

In Vue.js, I am aiming to achieve a certain behavior. To illustrate my point, here is the Js fiddle example that I am currently working on: https://jsfiddle.net/richardcwc/ukqhf54k/ //Canvas var canvas = document.getElementById('canvas'); var ct ...

Arrange Data Alphabetically using a JavaScript Loop

I have a unique program that extracts data from 2 different URLs. Using CSS, I automatically generate a sleek Business Card design in a 'for' loop. Now, I'm faced with the challenge of creating a Sort Alphabetical button based on "${users[co ...

Hover over a ListItem

Looking for advice on how to incorporate a Mouseover feature into a Material UI ListItem from the following link: http://www.material-ui.com/#/components/list. As the "SecondaryText" is limited to 2 lines, I am exploring options to display additional data ...

A fatal error has occurred in Node as it is unable to set headers after

Just getting started with nodeJs and I'm attempting to read a file from the system. It seems like I can view the file content in the console, but for some reason it's not displaying in the browser. Any ideas what I might be overlooking? var myD ...

Ways to eliminate the vertical scroll feature in a kendo chart

I am encountering an issue while loading a kendo chart inside grid-stack.js where I am unable to resize the height properly. Whenever I decrease the height, a vertical scroll appears which should not happen. I have tried setting the height to auto and refr ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...

Ensuring consistency of Angular route data and maintaining data synchronization

In my Angular application, I have a table that displays a set of items and allows inline editing directly within the table. The data is fetched from an HTTP API through a service, which retrieves the data and injects it into the application. The issue ari ...

How can you avoid Ajax calls from failing due to frequent requests?

Currently, I am utilizing ajax to retrieve some data. However, I have encountered an issue where the ajax request is triggered by hovering over a button, which could potentially result in multiple requests being sent and overwhelming the server, leading to ...

Are there any alternative methods for clearing form fields following a successful thunk dispatch in React?

When implementing a Post API call in Thunk, I dispatch a boolean success key for successful requests and an error message for errors. Now the goal is to clear form data upon success and display the error message upon an error. To achieve this, I utilize ...

Is there a correct way to properly duplicate a JSON array in Redux?

As a newcomer to Redux, I found the concepts somewhat confusing at first. For instance, imagine that there is an array in the redux state. const state = [ {show: false, id : '1'}, {show: false, id : '2'}, {show: false, id : &apo ...

What options do I have for sorting through my inventory using the search feature?

Having some trouble setting up isotope filtering on my search bar. I have managed to get the Isotope function working on checkboxes, but for some reason, my search bar isn't functioning as expected. I found a solution online for filtering results bas ...

Ordering ng-repeat in AngularJS using a separate arrayDiscover how to easily order your

Imagine I have an array containing keys in a specific order orderedItems=["apple","banana","orange]; and there is a JSON object that I want to display using ng-repeat but following the sequence specified in the array: {"fruits": { "apple":{ ...

Having trouble running `npm run dev` due to a webpack/babel conflict?

While attempting to execute npm run dev for a Vue project, I am consistently encountering the following output: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email ...

Activate response upon verifying website link

I am adding functionality to my HTML page where I want certain sections to be visible when the user clicks on a link. Initially, these sections are hidden using the CSS property display: none;. My aim is to make these sections visible when the user clicks ...

Fixing the mobile display issue with react-responsive-carousel

I am relatively new to ReactJS and I am looking to develop a responsive Carousel. Here is the code snippet that I have currently: To achieve a responsive Carousel for both desktop and mobile devices, I utilized the react-responsive-carousel library. The ...

I'm getting an error in Vue Router that says "Cannot read property 'push' of undefined"

I am experiencing an issue with page redirection. Despite ensuring the accuracy of my definitions, I am consistently encountering errors. Can anyone shed light on why this error persists? Your assistance is greatly appreciated in advance; your support mea ...

jQuery AJAX event handlers failing to trigger

It's driving me crazy! I've been using jquery's ajax for years, and I can't seem to figure out why the success, error, and complete events won't fire. The syntax is correct, the service it's calling works fine, but nothing hap ...

Issue encountered when summing numbers: There appears to be a continuous loop updating within a component's rendering function

Let's say I have a variable initialized as 0 and a method that increments this variable... However, when I try to use them, an error message is displayed: [Vue warn]: You may have an infinite update loop in a component render function. Here is the ...

Updating objects in Angular 8 while excluding the current index: a guide

this.DynamicData = { "items": [ { "item": "example", "description": "example" }, { "item": "aa", "description": "bb" }, ...