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 refresh the page settings for a table in Vuetify?

While I am currently on the second page of my pagination https://i.stack.imgur.com/xTYAU.png This is how my options are displayed https://i.stack.imgur.com/jPtNK.png After creating a record, I needed to make an API call to update the data in the table. ...

I can't seem to figure out why the removeChild() function is not functioning properly in my

Recently, I've been working on a search website where users can input either a partial or full name and then click a button to display a list of actors whose names contain that specific string in a hint-like fashion. These names are sourced from a MyS ...

Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks: https://i.stack.imgur.com/klPYV.png This is the middleware I am using: import { NextResponse, NextRequest } from "next/server"; export async functi ...

Expo background fetch initialized but not activated

During the development of my React Native app, I encountered the need to perform periodic background fetches from another server. To achieve this, I utilized two classes from Expo: import * as BackgroundFetch from 'expo-background-fetch'; import ...

AngularJS and adding to an array in the routing process

I'm currently working on creating a contact list with two different views. One view displays all the contacts and includes an option to add a new contact, which is represented by a button rather than a space to input information directly. The other vi ...

Facing an issue with displaying a component error in a mat-form-field in Angular 9

I am looking to develop a shared component for displaying errors in Angular Material. Here is my shared component pfa-share-error: <mat-error *ngIf="fieldErrors(fieldName).required && fieldErrors(fieldName)"> Required </mat-err ...

Amazon S3 Landing Page Featuring Contact Form

Although S3 is not a fileserver, it serves as an excellent tool for managing static websites. The majority of my projects are 99% static, making it ideal for this particular project. As an AWS Solutions Architect, I am struggling to find the most straightf ...

Encountering an async issue with npm exiftool in JavaScript

I'm facing issues with npm exiftool usage. (https://www.npmjs.com/package/exiftool) I'm attempting to perform some tasks using it. Iterate through image files in a specific folder Retrieve 'xpKeywords' data of each image file Write th ...

Ways to display URL parameters on an HTML page without using PHP

I'm currently working on a website using HTML (without PHP) and I'm facing an issue with displaying URL parameters on an appointment confirmation page. The appointment details are being successfully passed through the URL parameters, but I'm ...

Is it possible to determine when a Vue.js component instance has been successfully mounted?

Can we access a boolean in each component instance to determine when a component has been mounted? Something along the lines of: <template> <div> <span v-if="$mounted">I am mounted</span> <span v-if="$created">I am ...

Cordova - Fixed elements flicker/blink when scrolling

I have exhausted all possible solutions, ranging from -webkit-transform: translate3d(0,0,0); to -webkit-backface-visibility:hidden but none of them seem to resolve the issue of an element flickering/blinking/disappearing when scrolling on iOS with - ...

Angular does not alter the focus when a new component is loaded

Currently, I am working on resolving an accessibility issue with a screen reader in an Angular2 web application. When componentA (code shown below as Before) is loaded in Chrome, the entire browser window gains focus and the screen reader narrator announce ...

Using a Vuejs web component as an input element in a non-Vue web application: A step-by-step guide

After creating a web component with VueJs using VueCli3, the compiled output appears as follows: <script src="https://unpkg.com/vue"></script> <script src="./my-lib.js"></script> <my-lib></my-lib> This particular web ...

Having trouble executing the command ~$ vue add unit-mocha using vue cli 3

I am trying to integrate mocha as a unit testing plugin into my existing Vue project, which was set up using CLI 3 (vue create myProj). This pertains to Vue CLI version 3.0.0 and above, in which my current project is operating. Here is the error message ...

Error message encountered when deploying a Discord bot on Heroku: "SyntaxError: Unexpected token '??='"

I encountered an issue when trying to deploy a Discord bot that I created using Node.js on Heroku. The error message is as follows: 2021-11-05T00:00:10.334347+00:00 app[web.1]: > node . 2021-11-05T00:00:10.334348+00:00 app[web.1]: 2021-11-05T00:00:10.3 ...

Angular 1: selecting all checkboxes within an extensive ng-repeat list

I am encountering a performance issue with a table that includes hundreds of rows, each containing a checkbox. When I use the "Check All" option at the top to select all checkboxes in one go, the browser becomes unresponsive, especially in IE11 which is th ...

Unable to attach event listener within Shadcn Vue component in the latest version of Jhipster 8

My company's requirements dictate that I use the Vue 3 and Jhipster 8.0.0 framework. I have successfully installed the Shadcn Vue and it displays properly, but I am unable to assign any event listeners. <script setup lang="ts"> im ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

Issue with initializing MdTable in Vue Material when fetching data

After encountering a null error while trying to fetch remote data to initialize the MdTable component, I shared my issue here. The data is retrieved from a MySQL database as part of a Laravel 5.6 API project. Upon thorough investigation, it seems that the ...

Which is better for your website: SSG vs SSR?

Currently, I am diving into Nextjs and constructing a website using this framework. The site includes both public pages, protected routes (like user dashboard, user project details, and general user data), as well as product pages. I have been pondering h ...