challenges encountered with the clearTimeout() method in vue.js

I am currently working on implementing a shopping cart using Vue, but I am encountering some challenges. As I am new to using this library, it is possible that I am making some basic mistakes. Here is the issue I am facing:

When I add an item to the cart, I have an onclick function called expander(item) that performs the following actions:

this.addToCart(item);
this.show = true;
clearTimeout(this.timer);
timer: setTimeout(()=>{ this.show = false; }, 3000);    

Essentially, this function adds the item to the cart, makes the cart div visible, and then after a delay of three seconds, hides the cart div again.

However, the issue I am facing is that the clearTimeout(this.timer) does not seem to work. This means that regardless of my actions, after three seconds, the visibility of the cart div always reverts to false. From my research, it appears that I am implementing the timer reset correctly in the function.

My assumption is that I may need to declare the variable

timer: setTimeout(()=>{ this.show = false; }, 3000);
outside of the function in order for clearTimeout() to locate it at the beginning of my function. However, no matter where I declare it - whether in my data {} or outside the Vue instance - it does not seem to be recognized within my functions.

Therefore, my question is: how should I declare the variable? Is this even the root of my problem? Are there simpler solutions to this issue than what I am currently attempting to implement?

Thank you in advance!

Answer №1

When looking at the referenced code, pay close attention to this specific line:

timer: setTimeout(()=>{ this.show = false; }, 3000);

This line actually creates a labelled statement and does not store the timer handle anywhere. To store it in this.timer, you should assign it like this:

this.timer = setTimeout(()=>{ this.show = false; }, 3000);

(The timer: syntax is typically used to assign within an object initializer [{ ... }], not outside of it.)

Answer №2

  • Ensure there is a 1-second delay between each keypress event,
  • If the user presses a key, the setTimeout function is cleared and a new one is set with an additional 1-second delay
  • If the user does not press any keys within 1 second, the previous setTimeout function expires and triggers another function (a method in VueJs)
  • List item

I implemented this solution to verify if the user has finished typing before making an API call:

data: {
    search: '',
    time:null,
    },
watch: {
    search: function (search) {
        var self = this;
        console.log('Search keypress: ' + search);
        if (search.length >= 3) {
            if (this.time) {
                clearTimeout(this.time);
            }
            this.time = setTimeout( () => this.searchOnline(search), 1000);
            console.log('Search online or wait for the user to finish typing?');
        }
    },
},
methods:{
    searchOnline: function(search){
        console.log('Starting online search: ' + search);
        // axios call to API search endpoint
        console.log('Online search completed!');
    },
}

Answer №3

  • When using setTimeout, an id is generated
  • Store this id in a variable
  • Use this variable to clear the timeout using clearTimeout

According to MDN: The timeoutID returned is a positive integer that identifies the timer created by setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

In my experience with Vuejs, the following steps have worked for me.

data: {
myToid:null,
}, ....

methods: {
 myTofunction: function(){
    clearTimeout(this.myToid);
    this.myToid = setTimeout(() => {
        ...my function code...;
    }, 6000);
 }
}

Each time I call myTofunction, it clears any existing setTimeout id (stored in myToid) and then sets a new id.

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

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

Exploring the concept of $http/$q/promise in Angular

I am struggling to understand when $q/$http should trigger the onReject block. For example, if I have a simple call like this: $http.get('/users') .then(function(res) { return res.data; }, function(err) { console.log(err); }); If ...

Checking JSON formatted actions in Rails 4: A guide to testing

I'm in the process of testing a Rails application where all my actions return data formatted in json. An example of this is within the UsersController # POST /users.json def create @user = User.new(user_params) respond_to do |format| ...

Encountering a 404 error while using Node.js for app.get requests with Postgres as the

Currently, I am in the process of learning Node.js by following a tutorial that guides me on building a simple API. The tutorial utilizes a sample database for demonstration purposes, but I decided to use my own Postgres DB instead. However, when trying to ...

Unable to locate the specified script using node.js

Recently, I've started working with Javascript and Node.js. My current project is utilizing OpenMCT (https://github.com/nasa/openmct) and I'm facing an issue when trying to integrate a script as a plugin in an index.html file. Upon starting the N ...

What steps can be taken to ensure that the scale() function is given the highest priority

Trying to develop a program that generates a canvas graph based on some calculated data. To adjust for larger numbers, I attempted to scale the graph using ctx.scale();. However, every time I do this, the canvas goes blank! I even tried scaling the canvas ...

Should I use React with Spring Boot or just Spring Boot for this project?

My partner and I are collaborating on a project for our current semester course. As we delve into our research on potential technologies to use, it seems like Spring Boot for the server side along with MySQL or Postgres for the database are emerging as s ...

Should each HTTP request in a Node web app open a separate MongoDB connection?

I've integrated MongoDB into my Express.js Node web app. Here's what I have so far: // in app.js var mongodb = require('mongodb'); var mongourl = /* ... */; // These are just examples: app.get('/write', function (req, res) ...

What is the process for utilizing jQuery's advanced ticker feature to extract content from a text file?

I am currently implementing this code on my website: <script> var file = "http://newsxpressmedia.com/files/theme/test.txt"; function getData(){ $.get(file,function(txt){ var lines = txt.responseText.split("\n"); for (var i = ...

Retrieve text from a dropdown menu while excluding any numerical values with the help of jQuery

I am currently implementing a Bootstrap dropdown menu along with jQuery to update the default <span class="selected">All</span> with the text of the selected item by the user. However, my objective is to display only the text of the selected it ...

Troubleshooting: The issue of receiving a 403 error when trying to access

I'm currently using Codeigniter 3 and have encountered an issue with a script. When the code is in my HTML file, everything works perfectly fine. However, if I move the code to an external file, I receive a 403 error. The location of my JavaScript fi ...

How come an <a> tag is nabbing mouse clicks from a <canvas> element?

I have been experimenting with creating a 3D piano using three.js. Here is a snippet of the code I am currently working on: let renderer, camera, scene, light, keys, selectedKey; init(); render(); function init() { // Code for initializing renderer, ...

AngularJS has encountered an error due to exceeding the maximum call stack size limit

Utilizing AngularJS and a web API, I am fetching data from an SQL table. I have designed a function that populates input fields with values when a row is selected from an HTML table. However, I encountered an error during debugging when clicking on any row ...

Retrieving data from vue-i18n file with vue.js

How do I retrieve data from my locale.js file in the customer.vue file? Below are the code snippets: locale.js module.exports = { de: { labels: { customer: { salutation: 'Anrede', firstname: 'Vorname& ...

Retain the user's input in the text box even after the form has been submitted

Currently, I am tackling the challenge of creating a register form with an error handler to manage any mistakes made by users during registration. Once the form is submitted, potential errors are displayed to the user. To enhance user experience, I am ex ...

The Safari browser restricts interaction with password inputs but allows interaction with other types of input fields

My password input field is styled like this: <input class="genericButton" id="login-password" type="password" name ="password" placeholder="Password"> While everything functions correctly in Chrome, I encounter an issue with Safari. When I try to i ...

Deciphering HTML with AngularJS

We are currently working with AngularJS version 1.5.6 and facing an issue with HTML characters not being displayed correctly in our text. Despite trying various solutions, we have been unsuccessful in resolving this issue. We have explored numerous discuss ...

What could be the reason for my jQuery call displaying as undefined?

How can I extract a URL from an <a> tag and show the first paragraph of the linked page below the title? At the moment, it just shows 'undefined'. Here's my HTML: <section class="community"> <div class="news"> <ul cla ...

Keypress event not triggering in Android WebView when using HTML input

There seems to be a variety of issues on certain devices, such as Samsung and others, depending on the Android version, WebView version, and keyboard being used: keypress events are not triggered keydown and keyup events always show keyCode=229 keypress ...