Live updating time and date functionality using JavaScript

Is it possible to dynamically display the time elapsed from now without refreshing the page? I'm considering using the date-fns package for this functionality. Can I use a Watcher in Vue JS to monitor changes in real-time? Any assistance on this matter would be greatly appreciated.

Would the formatDistance method in date-fns be appropriate for achieving this goal?

Answer №1

If you are utilizing the composition API, here is a solution for your scenario.

One option is to incorporate the useTimeAgo composable from VueUse. This will provide you with a formatted string that updates at a specified interval.

Here's an example to demonstrate how it works:

import { useTimeAgo } from '@vueuse/core'

const eventDate = new Date(2022, 0, 1)

const timeAgo = useTimeAgo(eventDate, { updateInterval: 30_000 }) // Updates every 30 seconds

It's worth noting that you cannot set requestAnimationFrame as the interval like you can with the useNow composable. However, according to Antfu's explanation on GitHub:

useTimeAgo doesn't require high accuracy in timing, so using requestAnimationFrame would be inefficient and increase bundle size unnecessarily.

For more information, check out useNow on VueUse.

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

What is the best way to define a variable in EJS?

I need to populate my database array results on the frontend using EJS. The code snippet I'm using is as follows: var tags = ["<%tags%>"] <% for(var i=0; i<tags.length; i++) { %> <a href='<%= tags[i] %&g ...

Can we set a restriction on the maximum number of children a particular div can contain?

I'm trying to find a way to restrict the number of children in a div. The concept is that there is a selected commands div where you can drag and drop available commands (essentially buttons) from another div called available commands. However, I wan ...

Enable divs to be interactively chosen

I have created two selectable divs that function like buttons. By using the left and right arrow keys, I am able to select one of the divs with this code: document.addEventListener("keydown", keyDownDocument, false); function keyDownDocument(e) { var k ...

Text Input Recognition Chrome Extension with a Pop-Up Display Feature

One feature of the Chrome Extension I developed allows users to input a string into a textfield and check if any words entered match items in an array. If the user's string includes a specific word from the array, I want it to be replaced with a clic ...

Display an image from the API that rotates when hovered over with the mouse

Currently, I am fetching data from pokeapi.co and dynamically inserting it into a table. This data includes various stats and an image. My goal is to make the image rotate when hovered over. While creating the table, I added an id="pokeImage" dynamically. ...

Fixing the problem of digest overflow in AngularJS

I've been working on a code to display a random number in my view, but I keep encountering the following error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! It seems to be related to a digest outflow issue, and I&apo ...

Is there a way to access the parent element within the javascript function of an asp:CustomValidator?

Is there a way to access the parent element in the asp:CustomValidator JavaScript function in order to verify if the associated checkbox has been selected? For instance: I'm faced with this code: <tr> <th class="gray ...

Leveraging jQuery and Ajax for retrieving information from a JSON document

As a newcomer to JS, I have successfully set up a JSON file on my Express server. My code snippet looks like this: const data = require('./src/data.json') app.get('/search', function (req, res) { res.header("Content-Type",'app ...

Encountering a Django Channels issue while loading the JavaScript wrapper

After successfully running the server, the following appeared in my cmd prompt: System check identified no issues (0 silenced). January 21, 2020 - 17:43:42 Django version 3.0.2, using settings 'crm.settings' Starting ASGI/Channels version 2.4.0 ...

What is the impact of minifying Angular directives with controllers?

If my directive is defined as: myapp.directive('directivename', ... return { ... restrict: 'E', controller: MyController, ... } function MyController($scope, $somethingelse) { // Co ...

Setting the x-api-key header with HttpInterceptor in Angular 4: A guide

I am attempting to use HttpInterceptor to set the header key and value, but I am encountering the following error: Failed to load https://example.com/api/agency: Response to preflight request doesn't pass access control check: No 'Access ...

Issue with Ionic 2: Variable is altered but does not reflect in the HTML view

Hello everyone, I am new to the world of ionic 2 and I am facing a problem that I hope you can help me with. I have a variable that I want to display on my smartphone screen by placing it between {{ myVar }} in my HTML code. The initial display works fine, ...

PlateJS: Transforming HTML into data

Trying to implement a functionality where clicking on a button retrieves an HTML string. The objective is to have this rich text editor within React-Hook-Form, and upon form submission, the value will be saved as HTML for database storage. Below is the pr ...

Why is it necessary to utilize the super keyword when extending a React.Component?

What is the purpose of using 'super' in the code snippet below? What specific functionality from React.Component does it need to access with 'super'? If CommentList is already extending React.Component, why is 'super' necessar ...

Uncover the hidden href link that has been obscured using the code javascript:void(0)

Currently, I am in the process of developing a straightforward PHP script to extract the actual link from a website that conceals the real link/key using the javascript:void(0) approach. Upon inspecting the source code, I noticed that the href link is empt ...

Leveraging prop data to create dynamic router links in Vue

I am attempting to develop a feature that will dynamically update links on ion buttons depending on the props received. So far, I have: <template> <ion-button router-link :to "`$/+ {{subLink1}}" shape="round">{{linkName1}}& ...

Tips for writing unit tests for components using vitest in the latest version of Nuxt

I've been working on transitioning from Vue 3 to Nuxt 3. I've successfully written unit tests for my components using vitest in my Vue app, however, when running the same tests in the Nuxt app, I encounter the following error: Error: Failed to ...

The integration of a webview within an Ionic application

I have developed a mobile app using the Ionic framework and now I am trying to incorporate a webview using Chrome browser instead of the default browser. Initially, I used the cordova-plugin-inappbrowser plugin but found it to be unstable. I then tried t ...

Leveraging AJAX to send a form filled with dynamic content to multiple destinations

I have a hidden form that needs to be submitted to two different locations. The form is automatically filled using the .val method in jQuery. How can I write the ajax script to submit this form to two different locations? Is it possible to do this without ...

I'm having issues with my Vue CDN code, as the output is displaying {{ name }} instead of the

I'm struggling with the Vue part of my code in both my brackets and Atom editors. I've tried multiple links, including the unpkg link, but nothing seems to work. Here is the code I've been working with: index.html: <!DOCTYPE html> ...