Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with:

let time = 0
let activated = 0

function changePic() {

    if(activated == 0) {
        interval()
        activated++
    }
}

function interval() {
    setInterval(timer, 1000)
}

function timer() {
    time++
    document.getElementById("timer").innerHTML = time + " seconds"

}

I have omitted unnecessary code.

Now, I am curious about two things:

  1. How can I simplify this code further?
  2. What steps do I need to take to add a stop button to halt the timer?

It's important to note that the timer should only activate once until stopped, at which point it should reset to 0 upon activation again.

Answer №1

Utilize the setInterval method to obtain the timerId, which can then be used to stop the timer effectively.

let time = 0;
let intervalId;

function toggleTimer() {
    if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
        time = 0;
    } else {
        intervalId = setInterval(() => {
            time++;
            document.getElementById("timer").textContent = time + " seconds";
        }, 1000);
    }
}
<button onclick="toggleTimer()">Start Timer</button>
<div id="timer"></div>

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

Issue with Discord.js voice connection destruction函数

I've been attempting to implement a "Stop" command using the @discordjs/voice package, but I'm encountering an error. Despite my efforts to add some error handling, the issue persists. Below is the code snippet: async function stop(message) { t ...

Choose each day's time slot on the jQuery FullCalendar version 2.x

The code snippet below is a segment of the code generated by the FullCalendar jQuery plugin version 2. It has undergone some changes from version 1.x in terms of the classes it utilizes. <div class="fc-slats"> <table> <tbody> ...

The babel-preset-es2016 plugin is in need of the babel-runtime peer dependency, however it seems that it

While I am aware that npm no longer automatically installs peer dependencies, why do I still receive a warning after manually installing them? ➜ npm install babel-runtime -g /usr/local/lib └─┬ <a href="/cdn-cgi/l/email-protect ...

Troubleshooting z-index conflict when using :before pseudo element to emphasize list entries

I am experiencing an issue with highlighting items in a list generated by JSTree using the :before pseudo element. The z-indexes seem to be causing some trouble, as adjusting them results in the highlighting appearing either behind all links or in front of ...

Sending data retrieved asynchronously to child components' props

Currently, I am developing an application that fetches an array of news items from a remote source and showcases them on a webpage. After successfully calling the endpoint using $.getJSON(), as indicated by console logs, I integrated this call into the pa ...

The request does not include the cookies

My ReactJS client sends a cookie using this NodeJS code snippet: res.cookie("token", jwtCreation, { maxAge: 24 * 60 * 60 * 1000, // Milliseconds (24 hours) sameSite: 'None', // Cross-site requests allowed for modern browser ...

Acquiring the underlying code of websites within the local network

In the tool I am creating, it takes a URL as a parameter and retrieves the source code from that URL for analysis. The tool will be hosted on our domain, with the capability of analyzing web pages of sites within our internal network domain. Here is the Jq ...

Is it possible to identify when a key is pressed on any part of an HTML webpage?

I am currently seeking a solution to detect when a key is pressed on any part of an HTML page, and then showcase a popup displaying the specific key that was pressed. While I have come across examples of achieving this within a textfield, my goal is to m ...

Nothing is being returned when using JQuery AJAX POST

Having trouble identifying the issue, as all that seems to happen is the URL changes to "http://localhost/?search=test" when entering "test", for example. index.php <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Shifting a div element around the webpage and letting it fall into place if it intersects with another div using plain JavaScript

Check out this jsFiddle link. Upon opening it, you will encounter a moveable div. However, I am looking to enhance this functionality by allowing the div to disappear if moved to the 'trash' area. Essentially, when you place the moveable div in t ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

Ways to extract a value from an object with no properties using jQuery

In order to perform statistical calculations like Averages (Mean, Median, Mode) on data extracted from Datatables, I need the automatic calculation to remain accurate even when the table is filtered. While I have managed to obtain the desired values, extra ...

What could be the reason for the emptiness of my AngularJS scope object?

The code snippet in my controller looks like this: app.controller("weeklyLogViewer", function ($scope, $http){ $scope.allLogs = {}; $http({ method: 'POST', url: '../Utilities/WeeklyLog.php', data: $scope.dateSelected, ...

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

I am looking to conceal an element as soon as a list item is scrolled into view and becomes active

Is it possible to hide a specific element when the contact section is activated on scroll, and have it visible otherwise? How can this be achieved using Jquery? <ul class="nav navbar-nav navbar-right navmenu"> <li data-menuanchor="ho ...

What is the best way to retrieve text from the p tag and input it into the text field?

Looking to resolve a situation where two identical IDs exist and need to implement some JQuery. The objective is for the input value to automatically update itself based on changes in the text of the p tag. $(document).ready(function(){ ...

How about this: "Using jQuery, we detached the element with the class 'myClass', then cloned it. But wait, where did my nested table go?"

I'm facing an issue where I have a div containing a table that I want to reuse for multiple entries in a JSON database. <div class="myButton"> <table> <tr id="currentVersion"> ...

PHP is unable to show items containing special characters such as double quotes and apostrophes

I am facing an issue with ordering food items. Names that do not contain apostrophes work fine, but those like Pasqua Nero D'Avola Sicilia are causing problems. I have tried replacing ' with \', but the issue persists. Here is the relev ...

Having trouble editing a form with React Hooks and Redux?

Seeking assistance with creating an edit form in React that utilizes data stored in Redux. The current form I have created is displaying the values correctly, but it appears to be read-only as no changes are being reflected when input is altered. Any advic ...

Unable to utilize a custom function within JQuery

I'm facing an issue with using the function I created. The codes are provided below and I keep encountering a "not a function error." var adjustTransparency = function () { //defining the function if ($(this).css('opacity&apo ...