Setting a setTimeout function for a Vue function

Can clearTimeout be used for a setTimeout function assigned to a Vue Method? If yes, how can it be accomplished?

    methods: {
        timeoutController() {
          setTimeout(function() {
            this.controllerShown = false;
          }, 3000);
        }
....

Answer №1

new Vue({
      el: '#app',
      
      data: {
        timer: null
      },
      
      methods: {
        startTimer () {
          this.timer = setTimeout(() => {
            console.log("execute me")
          }, 3000)
        },
        // Stopping the timer before the setTimeout callback will prevent the callback from being executed
        stopTimer () {
          if (this.timer) {
            clearTimeout(this.timer)
          }
        }
      }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="startTimer()">start</button>
  <button @click="stopTimer()">stop</button>
</div>

Answer №2

What is the purpose of assigning a function to a Vue component's data?

By using the setTimeout() function, we can delay the execution of a specific task by 3000 ms and store the timer in this.timeout. Once the timer is set, it will not run again, regardless of any subsequent assignments.

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

Loading Objects with Material Textures Ahead in Three.js

I am faced with the challenge of preloading multiple obj+mtl files using Three.js, each with distinct file paths, and I need to trigger another function once all the objects have finished loading. Initially, I attempted to use a boolean variable that woul ...

Unable to download and install jspdf version 1.5.3

Currently, I am facing an issue where I need to convert HTML to PDF using jspdf 1.5.2. However, I am encountering an error that says "Cannot read property 'charAt' of undefined" when trying to utilize html2canvas. When attempting to upgrade to j ...

Filter an array containing objects within objects and use the reduce method to calculate the total value

Here is an array of objects that I'm working with: const data = [ { "order_id":38795, "order_type":"Music", "date":"2021-08-14", "name":"Concert ...

What could be causing the error when attempting to release this Node-MySQL pool?

My first attempt at utilizing connection pooling is with Node.js. I crafted a database connection module in Node.js to establish a single connection, which is then referenced within a pooling function for later use when passed to different modules. /* D ...

The Ajax script seems to be failing to update the PHP file along with its corresponding variable value

I have a simple form where upon clicking the "=" button, I want the calculated value to be displayed in file process.php. However, this functionality is not working for me. It seems that when the "=" button is clicked, nothing happens. The default value in ...

Conceal and reveal feature for multiple dynamic identifiers simultaneously

After submitting the form, I am dynamically creating buttons. <template name="workflow"> {{#each newaction}} <div class="btn-box" > {{> actioncardsubcontent}} <button type="button" class="cancelsub" >New Action</button&g ...

Incorporating a dynamic HTML editing button to every new row in a table using JavaScript

My application features a form that allows users to dynamically add new rows to a table using JavaScript: // Function to add a new account row if (tit.innerHTML === "Add Account"){ var table = document.getElementById(tableId); var row = table ...

What is the best method for choosing elements when I already possess a DOM element?

When you have a variable that contains a DOM element and need to select related elements, you can easily achieve this by wrapping it in a jQuery object. var myDomElement = document.getElementById("foo"); $(myDomElement ).find("a"); It is common for peopl ...

Switch up the blogs displayed depending on the category chosen using React

I seem to have hit a roadblock with my current issue. My challenge involves organizing and displaying blog posts according to their categories: const Posts = ({ state }) => { const data = state.source.get(state.router.link); const postsPerCategory ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

Ways to verify if a firebase timestamp surpasses the present date

Would you help me with comparing a timestamp field with the current date using JavaScript? This is what I have tried so far: // Initialize an empty array to store documents let myDocs = []; // Call the getDocs function and handle the response await getDo ...

Arrange the Proxy Array of Objects, the localeCompare function is not available

Encountering an error while attempting to implement ES6 arrayObj.sort(a,b) => a.property.localeCompare(b.property) syntax: Getting TypeError: a.property.localeCompare is not a function. Suspecting that localeCompare might not be in scope, but unsure ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

Tips for Locating an Element by Its Attribute in JQuery

I currently have a variable that holds a list of selects, and my goal is to filter out only those with a 'dependsOn' attribute set to 'EventType'. My initial attempt below doesn't seem to work as intended and returns a count of 0: ...

Numerous animated elements within A-frame

Is there a way to incorporate animation into an A-Frame glTF model, causing it to smoothly move 5 spaces to the left and then 5 spaces forward? Below is my current code: <a-gltf-model color="#FFFFFF" width="1" height="1" de ...

The Zustand store does not reflect changes when the URL is updated

I have a Zustand store connected to the URL. See the code snippet provided below. import { create } from "zustand"; import { persist, StateStorage, createJSONStorage } from "zustand/middleware"; const pathStorage: StateStorage = { ge ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

What is the best way to organize divs in a grid layout that adapts to different screen sizes, similar to the style

Is there a way to align multiple elements of varying heights against the top of a container, similar to what is seen on Wolfram's homepage? I noticed that they used a lot of JavaScript and absolute positioning in their code, but I'm wondering if ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

The challenge of handling scopes in Angular-seed

I am currently facing a challenge with creating a pre-routeProvider post. The problem I'm encountering is that $http is coming up as undefined, even though I am passing it to the function as per my understanding. I have made sure to declare angular.js ...