Is there a way for my code to detect when a function and a timeout are in progress?

Is there a way to disable my button after just one click, or when the timeOut function is running? Currently, I have code that allows the button to be clicked only if my moneyValue is greater than money, and it's working perfectly. Now, within that same if statement, I also want the button to be disabled when a certain condition is met (//if function is running). Any ideas on how to achieve this?

Here's the code snippet:

  data:{
    crashValue: 1,
    money: 1000,
    moneyValue: 0,
    betAmount: 0,
    buttonDisabled: false
},
methods:{
    placeBet(){
      let asd = this.money - this.moneyValue;
      this.money = asd;
      this.betAmount = 1000 - asd;
      this.startTimer();
    },
    checkAmount(){
      if(this.moneyValue > this.money // HELP NEEDED HERE !){
        this.buttonDisabled = true;
      } else {
        this.buttonDisabled = false;
      }
    },
    startTimer () {
      let interval = 90;
      if (this.crashValue > 2.15) {
        interval = 80;
      }
      // Additional conditions here...
      
      var tessst = setTimeout(this.crashFunction, interval);
    },
    placeBet(){
      let asd = this.money - this.moneyValue;
      this.money = asd;
      this.betAmount = 1000 - asd;
      this.startTimer();
    },
    checkAmount2(){
      if(this.moneyValue <= 0){
         this.buttonDisabled = true;
      } else {
         this.buttonDisabled = false;
      }
    },
    cashOut(){
      clearTimeout(this.tessst);
      console.log(Number(this.betAmount * this.crashValue).toFixed(2));
    }}
          <input @keyup="checkAmount(); checkAmount2()" v-model="moneyValue" class="numbImp" type="number" />
          <p>
            Your bet {{ betAmount }}
          </p>
          <button class="placeBet" :disabled="buttonDisabled" @click="placeBet(); checkAmount(); checkAmount2">Place bet</button>
          <button class="stopCrash" @click="cashOut">Cash out</button>
          <p>
           You currently have {{ money }} money
          </p>

Answer №1

To ensure your timeout function runs smoothly, make sure to declare a new flag called this.functionIsRunning and set it to true when initiating the timeout function. Then, when clearing the timeout function, remember to update this.functionIsRunning to false. While you haven't provided your exact timeout code, this setup should suffice. Make the necessary adjustments to your code as shown below:

data:{
    crashValue: 1,
    money: 1000,
    moneyValue: 0,
    betAmount: 0,
    buttonDisabled: false,
    functionIsRunning: false

  },
methods:{
    placeBet(){
      let asd = this.money - this.moneyValue;
      this.money = asd;
      this.betAmount = 1000 - asd;
      this.startTimer();
    },
    checkAmount(){
      if(this.moneyValue > this.money && this.functionIsRunning // I WANT HELP HERE !){
        this.buttonDisabled = true;
      }else{
        this.buttonDisabled = false;
      }
    },
    checkAmount2(){
      if(this.moneyValue <= 0 ){
        this.buttonDisabled = true;
      }else{
        this.buttonDisabled = false;
      }
    },
    cashOut(){
      clearTimeout(this.tessst)
this.functionIsRunning = false;
      console.log(Number(this.betAmount * this.crashValue).toFixed(2))
    }}

Answer №2

To implement this functionality, I recommend using a computed property as shown below:

<button :disabled="checkFunds">Click Me</button>

Here is the corresponding script:

computed: {
   checkFunds:function(){
      return this.moneyValue > this.totalMoneyAvailable && this.isActive ? true : false; 
   }
}

Answer №3

To determine whether the timeout is set or not, you can save the return value and then create a computed property based on your logic to disable the button.

data () {
  return {
    money: 1000,
    moneyValue: 0,
    timeout: null
  }
},

computed: {
  disableButton () {
    return timeout !== null || moneyValue > money
  }
},

methods: {
  startTimer () {
    ...
    this.timeout = setTimeout(this.crashFunction, interval)
  },
  cashOut () {
    clearTimeout(this.timeout)
    this.timeout = null
  }
}

Include in the template

<button :disabled="disableButton">Button</button>

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

What is the best way to duplicate a complete row?

I am looking to create a form that includes an "Add Row" button. When this button is clicked, a new row should be generated, identical to the last row. The rows contain dropdown values, and I want the new row to display the same dropdown options as the p ...

Transforming the date from JavaScript to the Swift JSON timeIntervalSinceReferenceDate structure

If I have a JavaScript date, what is the best way to convert it to match the format used in Swift JSON encoding? For example, how can I obtain a value of 620102769.132999 for a date like 2020-08-26 02:46:09? ...

A guide to entering information into an input field with JavaScript for logging in successfully

https://i.stack.imgur.com/TF51Z.gif https://i.stack.imgur.com/HHsax.png https://i.stack.imgur.com/HUztt.png When attempting to input text using document.getelement('').value="" , it doesn't behave as expected. The text disappear ...

Import data from JSON using JavaScript

I have a collection of txt files that contain custom content. The file names are stored in a JSON array. { txtFiles: ['./file1.txt', './file2.txt', './file3.txt'] } I am looking to use the require function in JavaScript t ...

Step-by-step guide on utilizing the material-ui AutoComplete feature to filter a table by selecting a key from a list and manually entering

I'm working on developing a filtering system similar to the AWS Dashboard, where users can select a filter key like instance state, which then displays the key in the input field and allows the user to enter a value to search for. I'm attempting ...

Populate Chart.js with a specific set of JSON data

As I delve into the world of JavaScript, I'm faced with a challenging issue that I need help resolving: I have a JSON file housing an array of data. What I aim to do is extract specific arrays from the month of August (Reports, Average, Global) and d ...

Setting the role attribute as "status" dynamically using VueJS

I'm searching for a method to define the role="status" attribute with vue.js. For instance: :role="{'status': isStatus}" <span class="result-total" role="status"> <span class="result-n ...

Deciphering the LocalDate and nested object array in an AJAX response

Seeking assistance, looking for solutions to two problems. Firstly, how can I display LocalDate in an ajax response? And secondly, how do I iterate over a list of Custom objects received in the ajax response? I am passing a List of Custom Objects and Loca ...

What is the method for incorporating a global function with a plugin to display notifications in Vue.js?

Recently, I encountered an issue while trying to create a global function using a plugin. Everything seemed to be working fine until I faced difficulties in displaying my notifications. Tired of repeating the notification display methods everywhere in my c ...

Retrieving information selectively using useSWRImmutable

Having issues fetching data using useSWRImmutable. The problem arises when attempting to display the fetched data inside the UserRow component. Even though I can successfully print the data outside of the UserRow component, any console.log() statements wi ...

Issues encountered in loading JavaScript with jQuery script

I am facing an issue with my jQuery script not loading correctly. When I click on the calculate button, nothing happens as expected. I made sure to copy and paste jQuery directly into the file for offline use, and also created a personal console due to res ...

Prevent validation on a particular input field with JQuery validator and Bootstrap

Is there a way to use JQuery validator to validate an entire form except for a specific input? Here is an example code snippet showing how this can be done: jQuery.validator.setDefaults({ debug: true, success: "valid" }); ...

What is the method for enabling or disabling a text field based on the chosen value in a b-form-select?

Can anyone assist me with enabling or disabling an input text field based on the values selected in a b-form-select element? Your help would be greatly appreciated. ...

When utilizing a wrapped v-text-field, it triggers warning messages and fails to update the data properly

Recently delving into the world of vue.js, I've been experimenting with creating a form using Vue, vuetify, and vuelidate. Oddly enough, when I don't wrap the v-text-field there are no issues, but as soon as I try to encapsulate it within compone ...

Is it possible to swap out images using srcset attribute?

Currently, I am facing an issue regarding changing the img on mobile and tablet devices to display different images. As a beginner with jQuery, I couldn't resolve it using that framework, so I am exploring options with html5. I am wondering if there ...

Exiting the Protractor timeout setting for Safari WebDriver

While I have experience with unit tests using Karma, my office is now interested in integration tests, specifically to test cross-browser capabilities. Protractor seemed like the best option for this, so I began working on some basic dashboard tests. Howev ...

Retrieve any webpage using AJAX

Hey there! I'm a beginner in AJAX and have a question that may seem basic to some. I understand that you can set up a page to respond to an AJAX call, but is it possible to request any page with AJAX? In other words, can all the functionalities of a ...

Using a custom attribute in jQuery allows conditional statements to be executed using the

I have been attempting to create an if/else statement in jQuery using a custom attribute called "data-id". I decided to name it this way because I thought I could utilize the .data() method in jQuery, but unfortunately, it did not work as expected. Below ...

Having trouble identifying whether a file is a picture or video based solely on its extension

My current challenge involves determining whether an uploaded file is a video or a photo. This distinction is crucial as it dictates whether the file should be sent to my telegram bot as a video or photo attachment. Despite having what seems like a logica ...

Cease the clicking action event

How do I terminate a mousedown function when the mouse is released? $('#manRun').mousedown(function(e3) { var manID = get_id(this); e3.preventDefault(); $(document).on('mousemove.moveMan', function(e2) { ...