Understanding setInterval and clearInterval in Vue.js 3: A Complete Guide

I am currently developing an application that relies on a timer to update variables every second. The implementation involves using the "setInterval" function to initiate the timer and the "clearInterval" function to halt it. However, I feel like my current approach may not be optimal.

My attempt involved defining the timer as a ref variable within the setup function and clearing the timer in the "onUnmounted" lifecycle hook. Here is an example snippet of the code:

<script setup lang="ts">
import { ref, onUnmounted } from "vue";

const timer = ref(setInterval(() => {/* Bla bla bla. */}, 1000));

onUnmounted(() => {
  clearInterval(timer.value);
})
<script>

Although this works, I question whether making the timer reactive is necessary. Are there alternative methods for achieving this task more efficiently, or does my existing code suffice?

Answer №1

If you have access to libraries, utilize them

import { useIntervalFn } from '@vueuse/core'

const { pause, resume, isActive } = useIntervalFn(() => {
  /* your custom code here */
}, 1000)

If not, create a composable function

function useIntervalFn(cb: () => void, ms: number) {
   let int: number = 0;
   onMounted(() => int = setInterval(cb, ms));
   onUnmounted(() => clearInterval(int));
}

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

Progressive Web App with Vue.js and WordPress Rest API integration

When creating an ecommerce website using Wordpress, I utilized Python for scraping data from other websites to compare prices and bulk upload products through a CSV file. My next goal is to learn Vue and transform the website into a PWA as it will be esse ...

Warning in Next.js: Each element in a list requires a distinct "key" property

Currently, I am in the process of building an e-commerce platform using Nextjs. My current focus is on enhancing the functionality of the myCart page, which serves as a dashboard for displaying the list of items that have been ordered. Below is the code s ...

Nested Popper component in MATERIAL-UI React - a Popper within a Popper

I am currently developing a calendar application. The issue at hand is that when clicking on a popper within another popper, both poppers close. This happens because the click outside event of the first popper triggers and closes it. I have a component c ...

Can Javascript be used to obtain someone's UDID?

Is it feasible to retrieve individuals' UDIDs when they visit your website? If this is achievable, could you recommend a helpful tutorial for me to follow? ...

Verify in Typescript if there is at least one value supplied

Looking for a solution: function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) { let result : string; if (!firstOptionalVariable && !secondOptionalVariable) { throw new E ...

Different Approach to Guarantee API

Here is the current structure of the promise executor: let p = new Promise((resolve, reject) => { }); It would be much cleaner if it were like this: let p = new Promise(r => { // r.resolve() / r.reject(); }); Is there a possibility to upd ...

initialize state using shorthand property in class components

I came across some code recently that caught my eye. It appears to be neat and organized, but there are a few things that seem out of the ordinary to me. Why is state = {} declared without a constructor? Additionally, why is load declared without using th ...

Troubleshooting the 'ReferenceError: requestAnimationFrame is not defined' error in Vuetify unit testing

Running vue run test:unit with certain Vuetify components is resulting in the error outlined below: ReferenceError: requestAnimationFrame is not defined at VueComponent.mounted (dist/js/webpack:/src/components/VTextField/VTextField.ts:229:1) a ...

Why won't my navigation bar stay in place when I scroll down on the screen?

I'm trying to create a sticky navigation bar that becomes fixed when the user scrolls down to 200 pixels, but it's not working properly. I want it to behave like in this example: import React,{useState,useEffect} from 'react' functio ...

retrieve asynchronous data from the server using ngrx

How can I retrieve asynchronous data from the server? I am looking to save this data in a global store for future updates. I'm having trouble grasping the concept of asynchronous calls, such as in Redux. While I was able to understand it with simpl ...

Create an array in JSON format that includes a JavaScript variable, with the variable's value changing each time a mouse

var question="What is your favorite color?"; var option="red"; var col=[]; When the user clicks, the variable value changes and values should be pushed in a specific format. I am new to JavaScript, please help me with this. Thank you. //On click, the var ...

Dynamic loading in React Plugin Architecture allows for flexibility in organizing and incorporating

My goal is to develop a Single Page Application on the client side that incorporates a plugin architecture. The requirement is for users to be able to place a package in a designated folder, which will then be loaded by the server after a restart. These pl ...

Angular - Display shows previous and current data values

My Angular application has a variable called modelResponse that gets updated with new values and prints them. However, in the HTML, it also displays all of its old values along with the new ones. I used two-way data binding on modelResponse in the HTML [( ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...

Looking to change the date format from 24/05/2021 to 24/May/2021 using jQuery or JavaScript?

My client prefers not to use a date picker, but wants to be able to type dates directly into a textbox and have them automatically converted to the format 24/May/2021 as they leave the field. I am looking for a solution using either Javascript or jQuery. ...

Overseeing the management of JavaScript dependencies

Our website is plagued with old frontend code that's in disarray. It's a mishmash of different versions of JavaScript frameworks and libraries being loaded. Some parts of the code have messy inline JavaScript that attempts to handle dependencies ...

The Splitter remains inactive until a peculiar series of actions is taken

Trying to troubleshoot this issue with a library called Split.js, which can be found here: https://github.com/nathancahill/Split.js I've encountered an interesting problem where I have to disable the height CSS property of my container, move the spli ...

Having trouble with Angular 2 and localhost/null error while attempting to make an http.get request?

In my Angular 2 webpage, I am using the OnInit function to execute a method that looks like this (with generic names used): getAllObjects(): Promise<object[]>{ return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response. ...

Issue with Nodemailer OAuth2 2LO authentication when deployed on Heroku

const { EMAIL_FROM, EMAILS_TO, USER, GMAIL_CLIENT_ID, GMAIL_PRIVATE_KEY } = process.env; let transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, auth: { type: &a ...

Guide on integrating Pug files as part of Vite module graph

Recently, I developed a custom Rollup plugin that allows the import of Pug files as HTML strings: // Custom Rollup Plugin for Vite Setup import { render } from 'pug'; export default function pug() { return { name: 'rollup-plugin-pug- ...