Using Vue.js, execute a function when there is input, but with a slight delay

Within my input field, I have implemented a method called activate triggered by v-on:input. This method is structured as follows:

export default: {
    data() {
        return {
            isHidden: true
        }
    },
    methods: {
        activate() {
            this.isHidden = false;
        }
    }
}

The isHidden property controls the display of an icon, serving as an illustrative example rather than essential functionality.

Currently, the activate function is triggered immediately upon user input. I'm exploring ways to introduce a delay using setTimeout. Here's what I attempted without success:

methods: {
    setTimeout(function() {
        activate() {
            this.isHidden = false;
        }
    }, 500)
}

Answer №1

Give this a shot:

functions: {
  engage() {
    setTimeout(() => this.notHidden = true, 500);
  }
}

Answer №2

Alternatively, you can achieve the same result without using an arrow function:

methods: {
    activate() {
        var self = this;
        setTimeout(function() { self.isHidden = false; }, 500);
    }
}

Answer №3

Firstly, establish a variable within your data:

data() {
    return {
        typing: Date.now()
    }
}

Next, within your methods, create a function that will trigger on keyup:

pendingSave(val){
    let saving = setTimeout(() => {
        this.saveItem(val) // method to call when user is finished typing
    },1203)

    if(val){
        saving
        if(Date.now() - this.typing < 1200) clearTimeout(saving)
        this.typing = Date.now();
    }
}

Within your HTML, you would include something similar to this:

<input v-model="title" v-on:keyup="pendingSave(title)" type="text" placeholder="Title" />

When a user clicks inside the input and enters a character, it triggers 'pendingSave()'. This readies the function to be called via setTimeout() in 1203ms. If the user types another character within 1200ms, it cancels setTimeout(). Otherwise, it executes the function saveItem() as intended.

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

Utilizing Angular to efficiently download and showcase PDF files

Presently utilizing https://github.com/stranger82/angular-utf8-base64 as well as https://github.com/eligrey/FileSaver.js/ for the purpose of decoding a base64 encoded PDF file that I am fetching from a rest API. It successfully decodes and downloads, ...

ReactJS error: Unable to access the setState property

As a newcomer to ReactJS, I have been facing some challenges. I recently familiarized myself with the ES6 syntax, and it claims that the following pieces of code are equivalent in meaning. 1. YTSearch({key: API_KEY, term: 'nba'}, function(vide ...

The Vue component appears to be missing from the HTML code

I recently began learning Vue.js in school, and for my first assignment I need to print a h2 from a Vue component. However, I am having trouble getting it to work. Below is the code for the Vue component that I have created. var app = new Vue({ ...

Live alerts on the AWS platform (serverless)

Currently, I am working on implementing real-time notifications for my web application in AWS using TypeScript and Vue. The setup involves an RDS instance (mysql), Node.js Lambda functions for the backend, and S3 for the application storage. I am wonderin ...

Error in Winston: Unable to determine the length of undefined property

I encountered an issue with my Winston Transport in the express backend of my MERN app. The error message reads: error: uncaughtException: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefi ...

A helpful guide on integrating a Google font into your Next.js project using Tailwind CSS locally

I'm planning to use the "Work Sans" Font available on Google Fonts for a website I'm working on. After downloading the "WorkSans-Black.ttf" file, I created a subfolder named "fonts" within the "public" folder and placed the font file in there. Be ...

Utilizing a Frozen Tensorflow Model with NodeJS for High-Performance Computing

I am new to tensorflowjs and js in general, but I have a trained model that I need to run on it. I have converted the model to json format, but I am having trouble feeding data into it: const tf = require('@tensorflow/tfjs') const tfn = require( ...

What is the best method for implementing a Twitch <script> tag within Vue.js?

In an effort to replicate the functionality I achieved in Angular here, I am now attempting to do so within Vue.JS (2.6+). My goal is to utilize the Twitch API for embedding a Stream, which currently only offers usage through inline HTML: <script src= ...

Managing checkboxes using node.js and mongoose

This particular ejs file showcases a form featuring multiple checkbox inputs generated by looping through a database. Upon submission, a post request is triggered, and this request is subsequently managed by the app.post <form action="/" m ...

Targeting props within a Class Component: A Step-by-Step Guide

I am currently working on a MultiStep Form project. On the final page of the form, my goal is to push all the collected data to Firebase. I have been utilizing props and states to pass values from one page to another. However, I'm facing an issue in t ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

Error: Required variable missing in AJAX Post request

When making an ajax call, I use the following code: o.open("POST",q,true); o.setRequestHeader("Content-type","application/x-www-form-urlencoded"); o.setRequestHeader("Content-length",p.length); o.setRequestHeader("Connection","close"); Here, q represent ...

What is the ideal JavaScript framework for implementing drag-and-drop, resize, and rotation features?

I am planning to create a web application that involves images and text with user handle functionalities such as drag-and-drop, resizing, and rotating. Although I have tried using JQuery UI js to implement drag-and-drop, rotate, and resize, I have encount ...

Dynamic Creation of a jQuery Selector

Dear, I'm facing an issue while trying to load data dynamically into a table using JSON format. The data is coming from a PHP file. However, despite my attempts, the table remains empty and no data is being displayed. function fetchTableData() { ...

Inaccurate data is being shown by the Ajax method

I have a question that I haven't been able to find a satisfactory answer for: Recently, I started learning about AJAX methods and I'm trying to post some information processed by a php page named page.php. In my HTML file, I've included th ...

Just ran $npm install and encountered an error message: "Module '../lib/utils/unsupported.js' not found."

Returning to work on a React project after switching from the Rails environment, I encountered an issue where I am unable to run NPM commands in my Mac terminal. Despite trying various solutions I found online, none seem to be effective. The real concern i ...

Nginx and Socket.io: Issues with client-server connection not functioning properly

Hello everyone! I am currently in the process of deploying my application, which utilizes React and NodeJs. However, I have encountered an issue with integrating Socket.io with Nginx. My approach involves editing the Nginx file using the command: sudo ...

Tips for exploring electron without launching additional windows

Is there a way to navigate between HTML pages within the same window without opening multiple windows in Electron? ...

Encountering a hydration issue in Next.js when attempting to refresh the page after switching languages (excluding English) with next-translate/useTranslation

I've encountered an issue with the useTranslation hook from the next-translate package in my Next.js project. Although all languages are being recognized, I'm facing a hydration error whenever I change the language and refresh the page. Below is ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; https://i.sstatic.net/p0Foo.p ...