Restart the Interval once it has been reset

Is there a way to restart the Interval after it has been cleared? I am trying to make a button clickable once every 11 seconds. I have disabled the button while the timer is greater than 0, and once it reaches 0, the button becomes clickable again. The current code I have seems to work, but if I call the setInterval() function multiple times, the timer starts counting down too quickly. Are there any solutions for this issue?

data:{
    sTimer:11,
    sDisabled:true,
    asd:null
  },
  methods:{
        testing(){
        this.sTimer--;
      if(this.sTimer == 0){
        clearInterval(this.asd);
        this.sTimer= 11;
        this.sDisabled = false;
      }else{
        this.sDisabled = true;
      }
    },
    specialAttack(){
      setInterval(() => this.testing(), 1000)
    }
  },
  created(){
    this.asd = setInterval(() => this.testing(), 1000);
  }
<button class="specialAttack" :disabled="sDisabled" @click="specialAttack(); testing()">Special Attack {{ sTimer }}</button>

Answer №1

It seems there are a few errors in your approach that need to be addressed. Firstly, if you want to accomplish this task, it is recommended to use the setTimeout function instead of setInterval. This is because setInterval will repeatedly execute after a set time interval, which could be causing the issue of it being called twice when you click the button. Furthermore, it would be wise to create a reusable function for this purpose and then call it during document creation, rather than creating two separate intervals and calling them individually.

By following these guidelines, your final code should resemble something like the following:

HTML

<button class="specialAttack" :disabled="sDisabled" @click="specialAttack();">Special Attack {{ sTimer }}</button>

Javascript

data: () => {
    return {
      sTimer: 11,
      sDisabled: false,
      asd: null
    };
},
methods: {
    specialAttack() {
      clearTimeout(this.asd); // Alternatively, you can also disable it here by using: this.sDisabled = true
      if (this.sTimer > 0) {
        this.asd = setTimeout(() => {
          this.sDisabled = true;
          this.sTimer -= 1;
          this.specialAttack();
        }, 1000);
      } else {
        clearTimeout(this.asd);
        this.sTimer = 11;
        this.sDisabled = false;
      }
    }
  },
created() {
    this.specialAttack();
}

You can see a functioning demo here:

https://codesandbox.io/s/sweet-feynman-gsjocn

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

Navigating with AngularJS Front-End Routing using ui-router

My routing in AngularJS involves using ui-router for managing states: $urlRouterProvider.otherwise('/Home'); $stateProvider .state('home', { url: '/Home', templateUrl: '/Home/Home', cont ...

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

Invoke this (public) function from within a private function

This is the JavaScript code I am working with: (Check it here) $(function () { function Cat() { this.Meow = function (sound) { alert("Meow: " + sound); } this.Kick = function () { MakeNoise(); ...

Determining the variance between two datepickers

I've been attempting to calculate the date difference between two datepickers using JavaScript. Despite looking at other resources, I keep running into issues when trying to multiply the date difference by the price. Can anyone guide me in the right d ...

Setting a radio button to be checked in AngularJS using stored data

I am facing an issue with the radio button for the account type. Even though it is correctly stored in the database, it does not display when I first load the page. However, upon clicking any of the radio buttons, it updates the value and shows as checked. ...

jQuery's height calculations for elements are inaccurate

I have a total of seven divs, each with the class "row". Initially, their content is hidden but there is a timeline that spans from the first row to the last one. The height of the timeline is calculated dynamically based on the combined heights of all row ...

Utilize Javascript to access and manipulate the input using the document

I have an input validator that checks if a user's email and username are not already registered on the website. My code looks like this: Javascript: $(document).ready(function() { $('#email').blur(function(event) { $.get(Ba ...

Learn the proper way to utilize the function(global) method by applying it to the current context with

I stumbled upon a JavaScript code snippet in this discussion that caught my interest. The code snippet appears as follows: (function(global) { // the function's logic goes here })(this); What is the correct way to invoke this function to run the ...

In Node.js and Express, it is important to note that a variable must be declared before

When I use the express action get('items'), I encounter an issue while trying to call an external JSON-API and display the API response in my local response. The error that I am currently facing states that the items variable is not defined with ...

What is the best way to showcase a JSON array in a tabular layout?

I have a JSON array structured like this: [ { id: "001", name: "apple", category: "fruit", color: "red" }, { id: "002", name: "melon", category: "fruit", color: "green" }, ...

The lack of definition for the props value poses an issue in React.js Hooks

I'm currently developing a notepad web application that utilizes React Hooks for managing state variables. In order to fetch data from an API, I am using the axios library. The retrieved data consists of objects with fields such as _id, title, status, ...

ng-table malfunctioning with an injection error

Encountering an error while using ng-table: angular.js:12332 Error: [$injector:unpr] Unknown provider: ngTableParamsProvider <- ngTableParams <- tableController http://errors.angularjs.org/1.4.2/$injector/unpr?p0=ngTableParamsProvider%20%3C-%20ngTa ...

Increase initial zoom for React Three Fiber OrbitControls to provide a wider view

I've been working on a project in React Three Fiber using this codesandbox for practice. My query regarding the demo is about setting a wider initial zoom in OrbitControls to view more small stars. Can anyone help with this? Below is the code snippe ...

Obtain the URL value using jQuery and place it inside a <span> element

How can I insert a href value into the span tag like this? <p class="name"> <a download="adja-lo.pdf" title="adja-lo.pdf" href="http://localhost/MatrixDRSnews/apps/Matrix/server/php/files/adja-lo.pdf">adja-lo.pdf</a> </p> ...

What is the method for retrieving values from an object using keys that are subject to change?

Here is the code snippet I am working with: bodyLength.forEach((el, i) => { console.log(`${values.bodyTitleEn2 + i.toString()}`); body.push({ title: [ { key: 'en', value: values.bodyTi ...

Creating connections between variables and elements in nested ngRepeats in Angular

I've been facing a challenge with my app where I need to update the comments section whenever a comment is added, edited, or deleted without having to refresh the page. I am using ngResource to handle queries for both articles and comments (e.g. $scop ...

Check out this handy guide on how to use jQuery for sliding effects: [link

My expertise in JS or jQuery is limited, so I am reaching out for your assistance. Take a look at this Slide Example for reference. Can you provide guidance on how to create a similar sliding effect with jQuery using the link provided? ...

unemployed with XMLHttpRequest not functioning

I have exhausted all recommended solutions for similar issues, yet this simple code refuses to work. My goal is to retrieve a message from the PHP code in the same file using XMLHttpRequest. <!DOCTYPE html> <head></head> <body> < ...

Issue with loading the main.css file

Getting Started Managing two domains can be a challenge, especially when trying to make them appear as one seamless website. In this case, I have ownership of and . Goal My goal is to merge the content of https://mauricevandorst.com/personal-page/index ...

Strange Behavior of ngIf and @Input in Angular 2

Despite console indicating false, NgIf appears to always evaluate as true. The issue stems from the component's HTML below: <product-component-tree itemSku="{{item.itemSku}}" selectable="false" classes="col-md-12 col-xs-12"></product-compo ...