I have been working on developing a Chrome extension for a StopWatch, but I am facing an issue where the Stopwatch resets automatically whenever I click

I am currently working on a stopwatch chrome extension and facing an issue where clicking anywhere outside the extension popup resets the stopwatch to zero. I would like the stopwatch to keep running until I manually stop it or close the browser. Can someone assist me in resolving this issue?

Below is the code from my Manifest.json file:

{
"name": "ClockSet",
"version": "0.0.1",
"manifest_version": 2,
"browser_action": {
    "default_popup": "index.html",
    "default_icon": "logo.png"
},
"icons": {
    "128": "logo.png"
}}

Below is the JavaScript code I am using:

//JavaScript code for Stopwatchconst 
// Timer Field
let hourElement = document.querySelector(".hour");
let minuteElement = document.querySelector(".minute");
let secondElement = document.querySelector(".second");
let millisecondElement = document.querySelector(".milliSecond");

// Button Field
let startButton = document.querySelector(".start");
let pauseButton = document.querySelector(".pause");
let stopButton = document.querySelector(".stop");

// Counter Variable
let hour = 00;
let minute = 00;
let second = 00;
let millisecond = 00;
let interval;

window.onload = () => clearFields();

startButton.onclick = function() {
    clearInterval(interval); // Clears any existing interval
    interval = setInterval(startTimer, 10); //
};
pauseButton.onclick = function() {
    clearInterval(interval); // Clears interval when pause button is clicked
};
stopButton.onclick = function() {
    clearInterval(interval); // Clears interval
    clearFields(); // Clears timer fields
};

function startTimer() {
    millisecond++;
    if (millisecond < 9) {
        millisecondElement.innerText = "0" + millisecond;
    }
    if (millisecond > 99) {
        second++;
        secondElement.innerText = "0" + second;
        millisecond = 0;
        millisecondElement.innerText = "0" + millisecond;
    }
    if (second > 60) {
        minute++;
        minuteElement.innerText = "0" + minute;
        second = 0;
        secondElement.innerText = "0" + second;
    }

    if (millisecond > 9) {
        millisecondElement.innerText = millisecond;
    }
    if (second > 9) {
        secondElement.innerText = second;
    }
    if (minute > 9) {
        minuteElement.innerText = minute;
    }
    if (hour > 9) {
        hourElement.innerText = hour;
    }
}

function clearFields() {
    hourElement.innerText = "00";
    minuteElement.innerText = "00";
    secondElement.innerText = "00";
    millisecondElement.innerText = "00";
}
.watch {
    margin: 20px;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aecc9b98939196909faec3c1c5c4dbc7c5c3dbc4d2d9c6d9cdd2d6">[email protected]</a>/font/bootstrap-icons.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="db7a4a4a2c1b2bbc8adbecdc2c4c6f9b7b9bcb1">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<section id="stopwatch">
        <div class="row watch">
            <div class=" col-3 hourDiv">
                <h3 class="hour">01</h3>
                <p class="hourTitle">Hour</p>
            </div>
            <div class="col-3 minuteDiv">
                <h3 class="minute">30</h3>
                <p class="minuteTitle">Min</p>
            </div>
            <div class="col-3 secondDiv">
                <h3 class="second">01</h3>
                <p class="secondTitle">Sec</p>
            </div>
            <div class="col-3 milliSecondDiv">
                <h3 class="milliSecond">99</h3>
                <p class="milliSecondTitle">Millis</p>
            </div>
        </div>
        <div class="buttons">
            <button class="btn btn-primary start button" title="Start"><i class="bi bi-play"></i></button>
            <button class="btn btn-primary pause button" title="Pause"><i class="bi bi-pause-fill"></i></button>
            <button class="btn btn-primary stop button" title="Reset"><i class="bi bi-arrow-clockwise"></i></button>
        </div>
    </section>

Answer №1

To ensure continuous operation of your code, it is important to run it within a background script rather than the popup script. The popup script terminates when the popup window is closed, causing any variables declared within it to be lost. By having the popup script send a command message to the background script whenever the user interacts with any button, the stopwatch can continue running even when the popup is not open. When the user opens the popup again, they can request the background script to provide the necessary variables (milliseconds, seconds, minutes, hours) for updating the stopwatch. This approach is compatible only with manifest version 2.

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

Guide on incorporating a glyphicon into a dropdown menu link by leveraging the link_to helper in Ruby on Rails

Just getting started here and I have a question... I want to include glyphicons on the links in a dropdown menu using the link_to helper in my Ruby on Rails app. This is the code I currently have: <ul class="nav_item pull-right"> <li cla ...

Running a script upon service initialization

Can code be run when a service is first initialized? For instance, if the product Service is being initialized, I'd like to execute the following code: this.var = this.sharedService.aVar; ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...

There seems to be an issue when trying to retrieve data from a JSON array stored

I have a SQL table with a column that stores JSON arrays. I am able to retrieve the data using Node.js, but when I try to manipulate the JSON array, I encounter errors consistently. Here is an example of my JSON array in the SQL database: { characters: [{ ...

Implementing Material UI datetime-local feature with no minute selection

Is there a way to hide minutes in a TextField with type = datetime-local? <TextField label="From" type="datetime-local" InputLabelProps={{ shrink: true, }} /> This is how it appears on my end: screenshot ...

increase the width of the side menu bar to accommodate more content on the Bootstrap

At the moment, the line that separates the content from the side menu stops at the side menu's content. However, the content is going to be longer than the side menu, causing the page to look uneven. I attempted to adjust the page-content d-flex but d ...

Omitting a specific item from the OrderBy function in an AngularJS table

My table is sorted by the properties "age" and "name", but I also have a row counter (counterR) that displays the number of rows in the table. I want to exclude the counter from being affected by the sorting because I want it to remain static and always o ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Difficulty with spacing in HTML/CSS styling

Here is what I'm currently working on: link to jsfiddle code * { margin: 0; padding: 0; } html { height: 100%; } header, nav, section, article, aside, footer { display: block; } body { font: 12px/18px Arial, Tahoma, Verdana, sans- ...

What could be preventing my bootstrap class from being applied as expected?

As a newcomer to HTML, CSS, and bootstrap, I am struggling with updating my stylesheet values in the preview. This is the button tag that I am working with: <button class="btn btn-primary btn-xl">Find out More</button> However, when ...

The instance is referencing the property or method "sendResetMail" during render, but it is not defined

I'm pretty new to Vue and struggling with an error message while trying to get a reset email modal working in my Vue project: The error says that the property or method "sendResetMail" is not defined on the instance but referenced during render. I ...

Attempting to showcase extensive content based on the selection made in a drop-down menu

As a newcomer to anything beyond basic HTML, I am seeking guidance and assistance (preferably explained at a beginner level) for the following issue. If I have overlooked any crucial rules or concepts in my query, I apologize. I aim to have each selection ...

Avoid clicking in areas outside the perimeter of the blue circle in the SVG

Is there a way to restrict clicking outside the blue circle? The goal is to only allow opening by clicking on the svg itself, This includes everything, even white space inside the svg. How can this be achieved in the code? The current behavior is that ...

Troubleshooting automatic login problem in VB 2013 settings

For my application, I am utilizing the most recent version of Awesomium's WebControl. The goal is for it to automatically log in when it reaches "accounts.google.com/ServiceLogin" by executing some Javascript. In my.settings.java file, I have the foll ...

Incorporate a tall button on the right edge of the division

I have successfully implemented a sidebar with the ability to hide or display it using this link. Now, I am looking to add a clickable bar on the right side of the div that can also trigger the hide/show functionality. After experimenting, I discovered th ...

Adding Google Map V3 markers dynamically through jQuery

I have been using jquery and the Google Maps V3 API to dynamically add markers to my Google Maps. Whenever I click on the button search_button, an AJAX request is sent to the server, which returns a JSON array of LatLng values corresponding to the results. ...

Is this loader going through a triple loop?

<style> .loader { position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 9999; background-repeat: no-repeat; background: url('images/page-loader.gif'); } </style> <script src="//ajax.googleapis.com/ajax/libs/jque ...

React: the function is returning as undefined

Description I am encountering an issue with a function in a functional component, as it keeps returning undefined. Despite having all the necessary data defined and accurate within the function including tableData and subtractedStats. This seems to be a ...

Returning to the previous page is done by navigating back using the previous URL in Next.js

Recently, I encountered a situation where I had implemented filters on a webpage. Upon applying the filters, the URL of the page would change and additional query strings would be appended to the end. This caused an issue when navigating back using the b ...

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...