I am interested in tracking the time elapsed when the browser is active

After recently embarking on the journey of developing my very first Chrome extension, I encountered the task of creating a timer that starts as soon as the browser is launched. The timer should increment every second in the format: 00:00:00 --> 00:00:01 --> 00:00:02. Below is the code snippet I have implemented for this functionality. Are there better alternatives out there?

$(function () {
    startCount();
});

function startCount() {
    timer = setInterval(count, 1000);
}

function count() {
    var time_shown = $("#realtime").text();
    var time_chunks = time_shown.split(":");
    var hour, mins, secs;
    hour = Number(time_chunks[0]);
    mins = Number(time_chunks[1]);
    secs = Number(time_chunks[2]);
    secs++;

    if (secs == 60) {
        secs = 0;
        mins = mins + 1;
    }

    if (mins == 60) {
        mins = 0;
        hour = hour + 1;
    }

    if (hour == 13) {
        hour = 0;
    }

    $("#realtime").text(timezero(hour) + ":" + timezero(mins) + ":" + timezero(secs));
}

function timezero(digit) {
    var str = digit + '';

    if (digit < 10) {
        str = "0" + str;
    }

    return str;
}

Answer №1

The code provided is not ideal for multiple reasons. It operates under the faulty assumption that it will never miss a second, when in reality it may miss some due to timeout/intervals limitations. Additionally, the calculation process within the code is unnecessarily complex. Instead, consider using the Date.now() method upon page load and utilize an interval to continuously update and calculate the time difference with the current time.

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

Updating the legend boxes of a chart in Chart Js to match the style of the graph lines

I need assistance updating the legend boxes of my graphs with graph line style. https://i.sstatic.net/zhi4L.pngActual Consumption https://i.sstatic.net/dAjlp.png Average Use https://i.sstatic.net/YMC7I.png Here is the code snippet I am currently using, ...

Encountering an issue with React Router v6 where calling `history.push('/')` results in an error of "undefined (reading 'pathname')" - the URL changes, but the page remains unchanged

Having an issue altering the page within a Redux Thunk action creator to redirect the user back to the homepage after form submission Although the URL changes when the action creator is triggered, the page itself remains the same Unable to utilize Browse ...

Is there a script available on this page that allows me to access the Google Chrome plug-in variable?

Could you kindly clarify if a script on the webpage is able to access variables from a Chrome extension? I have developed an extension for Google Chrome and am concerned about the possibility of the website owner where the extension is running being able ...

What additional requirements are needed for Rails and remote AJAX with the "true" setting?

I'm a bit confused about the purpose of remote:true in Rails forms. I initially thought that it required some Javascript to enable asynchronous functionality, but instead it seems to be causing issues with my page. Below is a simple index.html.haml f ...

Tips for storing and replicating jQuery events

I am working on saving jQuery events in a database. // This Function is called On Click function trackevent(event){ window.events.push(event) } $.each(window.events, function(i, item){ console.log(i +" - "+ $.parseJSON(item)); }); The events a ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...

Rzslider not functioning properly due to CSS issues

I am facing an issue where rzslider is not appearing in my app. However, when I copy the code to an online editor, it works perfectly fine. Below is the code snippet: var app = angular.module('rzSliderDemo', ['rzModule', 'ui.boo ...

Performing multiple actions with the same key in Jquery based on their position

My goal is to enable users to scroll through a list by pressing the down arrow key, and I have successfully implemented this feature. In addition, users should be able to load the next list when they reach the end of the current list. This functionality h ...

Select elements in jQuery using both a specific selector and a negative selector

I am currently working with a JQuery function that highlights a specific word and scrolls to it: $('article.node--article p, .video-title').highlightWordAndScroll({ words : search_word, tag : '<span class="found_key ...

After updating the INNERHTML, the NAV tag content is no longer functional

I am facing an issue with replacing the contents of a NAV tag that contains UL list items. The original HTML within the NAV tag works perfectly fine, but when I replace it with my own HTML - which matches the original word for word - the dropdown functiona ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

Maintaining checkbox state using fetch arrays

Included below is the code present on my site, pulling data for each season including numbers of home wins, win percentage, and win lsp. It functions correctly by creating a new table row for each season. Furthermore, there are two columns featuring filte ...

Displaying a specific column value from a custom table in a Wordpress database when a button is clicked

After integrating a custom table into my WordPress database, I developed a shortcode to connect it to specific pages on my website. The table consists of two columns: ID and coupon_code. This special table holds coupon codes that I want to display the val ...

Troubleshooting Problems with Ruby Arrays, JavaScript, and JSON

I am facing a challenge with rendering a highcharts plugin in my rails application. I suspect it could be related to the sql queries fetching data from the database and converting them into a ruby array that the javascript code fails to interpret correctly ...

Utilize jQuery to show a specific section of the page based on the hash in the URL

So, the inspiration for this project stemmed from a common issue I encountered: After hitting the register button, the PHP script processes it and displays an error, but the page remains on the login form. Here's the visual representation of the i ...

I am trying to access a value saved in a service in Angular 8 component and use it in other services. Can anyone help

Setting a value through a component export class UniqueComponent { constructor(service:UniqueService){ } count =0 ; onRefresh(){ this.service.count = 1; } } Using the value in the service UniqueService{ count:any; doSomething(){ //using count ...

Instantly change the default value with Ajax selection

My current setup involves using Ajax to populate a select HTML element with values from an array returned by PHP. Here is the Ajax code snippet: <script type = "text/javascript"> $(document).ready(function(){ $('#fds_categories&ap ...

TinyMCE - Optimal Approach for Saving Changes: keyup vs onChange vs blur

In the context of my Filemaker file, I am utilizing the TinyMCE editor. My goal is to automatically save any changes made by the user, whether it's typing, applying formatting, inserting an image, or making any other modifications. I have a function ...

Background loading of child application in single-spa

I'm currently working on setting up a Single-Spa micro frontend with Dynamic Module Loading in React. The user journey I have in mind is as follows: Root Application -> Authentication Application -> User Enters Details -> API Call -> Redir ...

What is the best way to make an element fixed vertically in a mobile browser while also enabling horizontal scrolling?

When using a Desktop browser, I have found a javascript code that allows me to vertically fix an element while still enabling horizontal scrolling. The element is repositioned with each scroll event. You can test this out by trying both horizontal and vert ...