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

Preserving Search and Filter Settings in jQuery Data Tables

I've been working with a datatable and I'm trying to figure out how to keep dropdown filters and search parameters saved when the page is reloaded, just like shown in the screenshot below. However, I also want these parameters to be cleared if th ...

Callback function not being triggered in Jquery's getJson method

I am currently faced with a javascript conundrum. Below is the snippet of code that I have been working on: $.get("categories/json_get_cities/" + stateId, function(result) { //code here }, 'json' ); ...

Incorporate 3 additional compound filters with shuffle.js

Is there a way to add a third compound filter to the existing shuffle.js code provided below? // ES7 will have Array.prototype.includes. function arrayIncludes(array, value) { return array.indexOf(value) !== -1; } // Convert an array-like object to a r ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

How can VueJS manipulate state with Mutation?

I have set up a Vuex Store that returns data on headers and desserts. The desserts object includes a property called display, which is initially set to false. In my project, I am using a component called Row within another component named Table. The Row co ...

``Can you provide guidance on excluding matching values from a dictionary object in a Angular project?

I've developed a function that takes a dictionary object and matches an array as shown below: const dict = { CheckAStatus: "PASS", CheckAHeading: "", CheckADetail: "", CheckBStatus: "FAIL", CheckBHeading: "Heading1", CheckCStatus: "FAIL", ...

Guide on transforming UTC time from the server to the local time of users during a GET request

I am currently facing a challenge where I need to verify if the date of the last time an element was clicked matches the current date. Due to my server generating the current date which is 5 hours ahead of my local time, there is a discrepancy causing the ...

Iterate through an Array of Objects and exhibit a single object property in HTML one at a time by utilizing Javascript

I am working with an array of objects that contain two properties: "quote" and "author". I have a container div where I want the quotes to be displayed one by one at an interval of every 2 seconds. Currently, it is showing one letter at a time instead of d ...

Tips on maintaining the numerical value while using JSON.stringify()

Having trouble using the JSON.stringify() method to convert some values into JSON format. The variable amount is a string and I want the final value in JSON format to be a number, but it's not working as expected. Even after applying JSON.stringify(), ...

Challenges arise when utilizing CSS3 animations in conjunction with transitions triggered by toggling a JavaScript class

Struggling to activate an animation while updating a class using JavaScript for a PhoneGap app. Planning on utilizing -webkit- prefixes for compatibility. However, the animations are currently unresponsive in Chrome during testing, both when applied to th ...

iOS device encounters failure with Ajax CORS request and redirect

I am experiencing an issue where a URL is being redirected to another domain by the server. My test code is very simple: $.ajax({ type:"GET", url:"{MYURL}", success:function(d){alert('response');} }) You can che ...

Here are the steps to pass the selected dropdown value to ng-repeat for ordering:

I have a dropdown box with options for filtering data in an ng-repeat by different criteria. How can I pass the selected value from the dropdown to the ng-repeat orderby? Here is my dropdown: <select name='filter_range' id='filter_range ...

Does every controller page need to verify the Login Function?

In my PHP pages, I have implemented the MVC Pattern by creating a controller page for each view page to interact with the Model page. However, I have only checked user login at the top of every view page and not in the controller page. This leaves a potent ...

What steps can I take to ensure that this input is neat and tidy

I need to implement conditional styling for my input field. The current layout is chaotic and I want to improve it. Specifically, when the active item is "Height", I only want to display the height value and be able to change it using setHeight. const [a ...

Vertical alignment in material-ui's Grid component is not functioning as expected

I have been working on this code snippet to center a button both vertically and horizontally. However, it seems like the button is not positioned correctly along the vertical axis. Any advice or guidance would be greatly appreciated! Could someone assist ...

Remove elements from an array based on the indices provided in a separate array

1) Define the array a = [a,b,c,d,e,f,g,h,i,j]; using JavaScript. 2) Input an array 'b' containing 5 numbers using html tags. This will be referred to as the 'b' array. 3) Insert elements into array 'b' ensuring they are alwa ...

The Google reCaptcha reply was "Uncaught (in promise) null"

When using reCaptcha v2, I encountered an issue in the developer console showing Uncaught (in promise) null message regardless of moving the .reset() function. Here is the console output: https://i.stack.imgur.com/l24dC.png This is my code for reCaptcha ...

Tips for enforcing a new line for each attribute in Vue using Prettier within the VS Code environment

I am currently using Prettier Version: 9.5.0 for Vue in VSCode. This is the code snippet I'm working with: <q-select label="Fruits" :options="['apple', 'mango']" /> This is how I want Prettier to format ...

Why is a question mark added to the URL when the login button is clicked

I've encountered an issue where clicking this code for the first time redirects me to localhost:8080//? instead of localhost:8080//admin.html. Any idea why this is happening? $("#admin-login").click(function(){ var data = {"username": $("#admin ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...