`How to prevent Timeout function from randomly occurring`

I have a value that increments by 0.015 every 90 milliseconds indefinitely. Now, I want to implement a feature where this incrementing stops randomly upon clicking a button. I have written code for it but unfortunately, it is not functioning as expected.

data:{
 crashValue: 1,
},
methods:{
    crashFunction: function() {
      this.crashValue += 0.0150;
      this.startTimer();
    },
    startTimer () {
      let interval = 90
      if (this.crashValue > 2.15) {
        interval = 80
      }
      if (this.crashValue > 3.15) {
        interval = 70
      }
      if (this.crashValue > 4) {
        interval = 60
      }
      if (this.crashValue > 6.15) {
        interval = 55
      }
      if (this.crashValue > 8) {
        interval = 48
      }
      ... additional conditions ...
      
      this.tessst = setTimeout(this.crashFunction, interval);
    },
    randomStop(){
      let randomNumber = Math.floor(Math.random() * 5000)
      console.log(randomNumber)
      clearTimeout(() => this.startTimer(), randomNumber)
    },
}
<button class="stopCrash" :disabled="disableCashOut" @click="cashOut(); randomStop()">Cash out</button>

Answer №1

According to the clearTimeout documentation, the only parameter required is an ID generated by a setTimeout function.

To end your loop, you must provide the correct value, such as clearTimeout(this.tessst).

If you want the clearTimeout to be executed after a random time interval, you will need to set up another setTimeout. See the example below for demonstration:

var count = 0;
var timerId = null;
function startTimer() {
  console.log(++count);
  timerId = setTimeout(startTimer, 1000);
}
function stopTimer() {
  var rnd = Math.floor(Math.random() * 5000);
  console.log("Stopping in " + (rnd / 1000) + " seconds");
  setTimeout(function() {
    clearTimeout(timerId);
    console.log("Stopped");
  }, rnd);
}
startTimer();

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

Retrieve the keys from the initial object within an array of objects

I am looking to extract a list of unique keys from an array of objects. arr =[ {id: 1, desc: "", name: "", objectives: Array(3), …}, {id: 2, desc: "", name: "", objectives: Array(3), …}, {id: 3, desc: "", name: "", objectives: Array(3), …}, ...

ever-evolving background-image with dynamic CSS styling

Being new to both PHP and Javascript, please excuse any mistakes in my explanation. I have information stored in a PHP array that I bring to my index page using the function below (located in a separate file called articles.php that is included in my index ...

Chromium browsers exhibit strange behavior with AngularJS orderBy, causing issues with clearing sorting selections

There is a particular issue that is really frustrating me in one of my projects. The code I have is quite similar to this example (I tried to replicate it as closely as possible, but the actual code doesn't seem to be relevant because I can't re ...

Angular Ordering Map Object

Having an issue that I need help with: I have generated a key-value list and I am looking to sort it in descending order. As you can see in the stackblitz example, I have demonstrated how I create the list and attempt to sort it using different methods. Ho ...

Database Submission of Newsletter Information

I recently grabbed the following code snippet from a YouTube tutorial (shoutout to pbj746). Everything appears to be functioning correctly except for one crucial issue - the submitted data isn't showing up in the database! I've thoroughly checked ...

Error encountered on Next.js boilerplate development server

As I embark on my journey to learn next.js, I decided to install create-next-app and attempted to start a development server without making any changes to the boilerplate code provided. However, I encountered the following error: ./styles/globals.css Globa ...

Make sure to scan for duplicates prior to inserting into a JavaScript array

I am working on a React function that involves adding an object to a JavaScript array. Here is the code I have so far: selectAnimalHandler = (animal) =>{ console.log(animal.id) if(this.state.animals.find(ani => ani !== animal )){ this.s ...

Styling with CSS Variables and Transforming Elements

After conducting thorough research both on this platform and via Google, I have yet to find a solution to my query: "how can CSS variables be utilized in a CSS transform?" Within the HTML header, three CSS variables and their fallback values are declared: ...

Browse through content without displaying the page title on the navigation bar and without the use of frames

When I sign into certain websites, I have noticed that the address displayed is often something like this: https://examplesite.com/access Even though all the links on the landing page are clickable and functional, their corresponding addresses never show ...

I'm encountering an issue when trying to build a React application

Unable to perform EPERM operation, the command "mkdir c:" is not found when trying to create a React app using npx create-react-app myapp ...

Unlimited scrolling with jQuery/Ajax

I am currently working on implementing infinite scroll functionality using ajax, php, and mysql in my web application. However, I am facing difficulty in loading new content only when the user reaches the end of the page. Currently, all the data is loaded ...

An essential component of Chai assertion is the inclusion of "or"

While attempting to iterate through a list of elements, I am looking to verify that the body contains either of two values. However, the current assertion method only allows me to check for one value: expect(cellText).includes(toDateFormat); Is there a wa ...

Correcting the invalid syntax due to EOF issue

How can we resolve the end of file error? The brackets appear to be valid based on ecma standards, but it's not clear what is missing. After using jsonlint, this error was found: *Error: Parse error on line 16: ...States" }] }]}{ "i ...

Utilizing JQuery and PHP to perform basic division on a read-only form field

After searching all over the internet, I still can't find a solution to my problem. Here's what I'm trying to achieve: I have an input text field where users enter a number. Once they enter the number, I want it to be automatically divided ...

Can fog be applied from a fixed location within a three.js scene without being tied to the camera's position?

Is it feasible to render fog in such a way that an avatar on a terrain remains clear while the surrounding area gradually fades into the mist, especially when the camera is positioned overhead at a distance? ...

Transitioning from a traditional CURL method to utilizing AJAX and XMLHttp

I'm currently facing a challenge converting the curl code from an API named TextRazor to AJAX XMLHttp due to limitations on the platform I am working with. Despite trying various solutions shared by the community, I have been unsuccessful in retrievin ...

Retrieving information from JSON files using AngularJS

Here is a JSON object example: [ { "user": "A220", "shorttext": "shanghai", "reportedBy": "S,A", "questions": " [{\"question\":\"Q1\",\"is_mand\":\"0\",\"type\":\"text\",\"a ...

Utilize ethereumjs-wallet in your web browser as a standalone module

I am looking to generate a wallet (which includes creating an account address and private key) directly in the browser without the need to connect to a node. It seems that in order to utilize web3.js, a provider (such as Metamask or localnode) needs to be ...

Issue with activating a Modal through a button inside a table row on React

I'm currently working on two files: Modal.js and Users.js. Users.js features a table with an API get query linked to it, and in the last column of the table, there's a dropdown for each row that contains three buttons: View, Edit, and Delete. My ...

What is the best way to arrange groups in a specific order?

At the moment, the response sent back to the client-side appears in a specific structure: [ { "categoryName": "Orders", "categoryItems": [ { "group": "Group B", "groupSe ...