Tally time tracker in Google Chrome Expansion

Can anyone provide guidance on creating a count-up timer that continues running in the background? My goal is to display seconds, minutes, hours, days, and months. I specifically would like it to only reset when manually clicked on reset.

Appreciate any help!

Answer №1

Take some time to understand the following example program.
The system clock functions as you expect, and we simply make reference to it.
Counting months can be challenging due to the varying number of days in each month (28, 29, 30, or 31).

popup.js

const elmCounter = document.getElementById("counter");
const elmReset = document.getElementById("reset");

let lastTime = localStorage["lastTime"];
if (lastTime == null) {
  lastTime = new Date();
  localStorage["lastTime"] = lastTime;
}
else {
  lastTime = new Date(lastTime);
}

counter();

elmReset.onclick = () => {
  lastTime = new Date();
  localStorage["lastTime"] = lastTime;
};

async function counter() {
  while (1) {
    const nowTime = new Date();
    let diffTime = nowTime.getTime() - lastTime.getTime();
    diffTime /= 1000;
    diffTime = Math.floor(diffTime);
    const day = Math.floor(diffTime / (24 * 60 * 60));
    diffTime -= day * 24 * 60 * 60;
    const hour = Math.floor(diffTime / (60 * 60));
    diffTime -= hour * 60 * 60;
    const min = Math.floor(diffTime / 60)
    const sec = diffTime % 60
    elmCounter.innerText = day + "," + hour + "," + min + "," + sec;
    await new Promise(r => setTimeout(r, 500));
  }
}

manifest.json

{
  "name": "hoge",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html"
  }
}

popup.html

<!DOCTYPE html>

<head>
  <style type="text/css">
    * {
      font-size: xx-large;
    }
  </style>
</head>

<body style="min-width:250px;min-height:100px">
  <div id="counter"></div><br>
  <input type="button" id="reset" value="reset">
  <script src="popup.js"></script>
</body>

</html>

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

Tips on preventing the initial undefined subscription in JavaScript when using RxJS

I am having trouble subscribing to an object that I receive from the server. The code initially returns nothing. Here is the subscription code: ngOnInit() { this.dataService.getEvents() .subscribe( (events) => { this.events = events; ...

Insider's guide to showcasing code in vibrant colors using Python Django

Context: I am currently working on a Python Django web application and need to showcase code snippets in the browser with syntax highlighting. An example of the code snippet I want to display would be: if True: print("Hello World") I am look ...

A guide to resolving the issue of spacing out three adjacent elements in HTML/CSS

As I work on creating my personal website, I have encountered an issue with three elements that are supposed to be side-by-side. My desired structure is depicted in this link: https://i.sstatic.net/eQEf3.jpg However, the middle element is not responding t ...

Retrieve the content of the nearest 'td' element using the '.closest()' method, then locate the desired

I am struggling to assign the value from a <td> to a variable. My approach involves utilizing the closest() and find() methods in jQuery to locate the desired <td>. Interestingly, when I use alert on the <td>, it displays the correct val ...

JQuery ConcealAllRevealOne + Clickable Link to Expand DIV

My JQuery function, HideAllShowOne, allows me to easily toggle visibility of sections on my website: <script type="text/javascript" language="JavaScript"><-- function HideContent(d) { document.getElementById(d).style.display = "none"; } function ...

Exceedingly High Outputs from the Haversine Formula

I am currently utilizing the Haversine formula in order to compute the distance between two specific points on the earth's surface. Below is the code snippet I am using: var app = angular.module('app', []); app.controller('firstCtr ...

Interact with a Firebase database table using Node.js

I recently imported data into a table called users in Firebase, and here are the details: { "users" : [ {"id": 1, "fcmToken" : "APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG...", "fName" : "John", "lName" : "Doe", "phone" : "978677086 ...

Confirm that only the days of the present month are eligible for selection

I have been given the responsibility of validating a date field that is populated when an invoice is created. The date field consists of a text box and three button objects allowing users to select a date from a calendar, input today's date, or remove ...

Assign a class while directing visitors away from a particular webpage

Can a div have a class added on page load, but only when redirected from a specific link or page? I currently have an <a href="marketing.php" id="openMyMaterialTab"><button class="secondaryAction">See all</button></a> link on my la ...

creating a div element with a height that matches its content dimensions

I'm having trouble creating a navigation bar because the outer div isn't matching the height of the unordered list inside it. I attempted using display:inline-block as well, but it didn't solve the issue. Here is the HTML: http://jsfiddle ...

When links are hovered over, the cursor hand does not vanish even when using the style code "cursor: none;"

Currently, I am attempting to customize my cursor so that it only changes when hovering over links. Instead of setting cursor: none for the entire body, I am working on removing the default hand cursor using JavaScript. Despite the inspector showing that ...

Using xhttp to send the username and password to a specific URL

I'm looking to extract data from the webpage example.com/something.aspx?id=1, but this particular page can only be viewed after logging into the site. To tackle this, I have implemented a script that logs in the user first and then proceeds to retrie ...

When accessing the '/contact' route, I aim to maintain the existing view of the previous routes while displaying a modal window

When it comes to the design of my website, I have decided not to include a separate contact page. Instead, I want a modal to appear when the /contact link is clicked. However, I am facing two challenges: a) If someone directly lands on '', I wan ...

php Use cURL and the DOM to extract content with specified CSS styling

Unclear in the title, I want to copy all content from a specific div on an existing webpage (not owned by me). The code successfully extracts the content. Extractor code: // Get Data $curl_handle=curl_init(); curl_setopt($c ...

What are some ways to adjust the size of the option field in a select menu?

In my ionic popup, I have a HTML property called select with nested options. Below is the code snippet along with the applied CSS. My query is how can I set the white space to occupy the entire area of the select? https://i.stack.imgur.com/iPqAa.png http ...

I'm seeking guidance on handling complex relationships with Mongoose. Please provide a specific challenge example for a quick solution. Thank you

While I am skilled in using sequelize with node, angular, express etc., I am just beginning to delve into the M part of the MEAN stack by learning mongoose. However, I'm unsure of MongoDB's capabilities when it comes to organizing data in the dat ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

How can we filter the input type file browse window to display only image files?

I'm trying to figure out how to filter the window popup so that it only shows image files when I click on the input type file. <input type="file" /> Any help would be greatly appreciated as I have been struggling to find a solution for this. ...

What could be the reason behind receiving information from a mongodb database that seems to be empty?

I have been working on a todo application, and I am facing an issue with the ng-repeat directive in my code. It seems to create five todo boxes even when the database is empty. This may be related to the loadData function that I am calling, but I am unable ...

Navigating through Switch cases and If Statements with multiple arguments can be complex for beginners in the world of JavaScript

Hi there, I have a specific case that I'm struggling to find a solution for. I am using Angular with a Firebase back-end to retrieve true or false values from a variable called ref. The variable contains 4 properties with either true or false values - ...