JavaScript autostop timer feature

An innovative concept is the solo cookie timer that holds off for one hour before resuming its function upon user interaction.

No luck with Google. https://jsfiddle.net/m6vqyeu8/

Your input or assistance in creating your own version is greatly appreciated.

<!doctype html>
<html>
    <head>
        <title>cookie timer</title>
        <meta charset=utf-8>
    </head>
    <script>
        let initialValue = 0.50000096;
        let multiplier = 0.00000001;

        // Cookie functions
        let getCookie = (c_name) => {
            let i, x, y, ARRcookies = document.cookie.split(";");
            for (i = 0; i < ARRcookies.length; i++) {
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                x = x.replace(/^\s+|\s+$/g, "");
                if (x == c_name) {
                    return unescape(y);
                }
            }
        }

        let setCookie = (c_name, value, exdays) => {
            let exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            let c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        }

        // Check last updated time
        let lastUpdated = getCookie('lastUpdated') * 1;

        if (!lastUpdated) {
            lastUpdated = Date.now();
            setCookie('lastUpdated', lastUpdated, 9999);
        }

        // Calculate difference and update cookie
        let diff = (Date.now() - lastUpdated) / 1000;
        let cu = (diff * multiplier) + initialValue;

        // Update display and handle incrementation
        let doCu = () => {
            document.getElementById('cu').innerHTML = cu.toFixed(8);
            cu = cu + multiplier;
        }

        document.write("<div id='cu' style='text-align: center; font-size: 40pt'></div>\n");

        setInterval(doCu, 1000);
        doCu();
    </script>
  <body>
  </body>
</html> 

Answer №1

If you want to pause and resume the counter, it's important to save the return value of the setInterval function and either clear it or create a new one for pausing and resuming. Here's an example:

let interval = setInterval(doCu, 1000);
doCu();

function stop() {
  clearInterval(interval);
}

function resume() {
  interval = setInterval(doCu, 1000);
}

Add this code to the end of your script and include two buttons like the following to test it out:

<button onclick="stop()">
  Pause
</button>
<button onclick="resume()">
  Resume
</button>

To automatically stop the timer after one hour, you can use the following code:

// Stop the timer after one hour has passed.
// setTimeout calls the stop function (which is used to pause the timer as well) after 1 hour
// 1000 milliseconds equal 1 second. Multiply by 60 for minutes. Multiply by 60 again for hours
setTimeout(stop, 1000 * 60 * 60);

If you want the timer to stop after an hour from the moment you click resume, modify the resume function like this:

function resume() {
  interval = setInterval(doCu, 1000);

  // When you resume the timer, add a timeout so it will stop in an hour.
  setTimeout(stop, 1000 * 60 * 60);
}

I have made updates to the fiddle so you can see the complete implementation.

Check out the updated JSFiddle link here

EDIT:

  1. Implemented timer stopping after an hour
  2. Changed pause function to stop for clarity
  3. Enabled ability to stop timer after an hour following resume

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

Obtaining POST information from Web2py to a personal HTML document

Dealing with heavy jQuery cross-domain issues, I have turned to using web2py as a workaround. I am sending POST data from a local HTML file to my web2py server, which then makes a Python POST request to a second server (solving the cross-domain problem) a ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

Images in the JavaScript menu are not remaining fixed in place

Can someone help me with my website? I'm having trouble with the menu for different pages, it should stay gray for the active page. It was working fine before I switched to Wordpress, but now I'm not sure what the issue is. Could someone take a ...

How can data be shared between two functional child components in a React application?

I've been researching on Google quite a bit on how to transfer props between functional components, but it seems like there isn't much information available (or maybe I'm not using the right keywords). I don't need Redux or globally st ...

Emulating a Javascript API request

I'm looking to practice simulating API calls for a VueJS application. Currently, I am fetching data from a hardcoded JSON file that I've created. Within my App.vue: <template> <p>{{ teams.yankees.city }}</p> // Output will b ...

Could you confirm if this is a TypeScript function?

Recently, while delving into the vue-next source code, I stumbled upon a particular line that left me puzzled. Due to my limited experience with TypeScript, I found myself struggling to grasp its purpose. Could someone clarify if this snippet constitutes ...

Encountering an issue with double quotes formatting in Spring Boot applications

Currently, I am developing an application where I need to pass data from a Spring Boot controller to a template using Thymeleaf. Everything was going smoothly, until I encountered an issue when trying to send JSON data. I noticed that the double quote (" ...

When _.template is evaluated in Node JS, it freezes and encounters a ReferenceError causing the program to halt

I've noticed a strange issue when using http://underscorejs.org/ with Node JS: If a reference error occurs while evaluating a template function, Node JS will become unresponsive! Examples: EXAMPLE 1: SUCCESSFUL SCENARIO: var template = "<%= tes ...

Adjust words to fit any screen size as needed

Looking for a small program that can dynamically change a word within an SVG? The goal is to create an effect where regardless of the word or group of words, they always stretch along the entire height (due to a 90-degree rotation) by adjusting the font si ...

Monitoring Twitter bootstrap modal for scrollbar reaching the bottom

Currently, I am working with Twitter Bootstrap modal and facing a challenge in determining how to detect when the scrollbar of the modal reaches the bottom using either JavaScript or jQuery. https://i.stack.imgur.com/0VkqY.png My current approach involve ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...

The fixed left div and scrollable right div are experiencing issues with their alignment

I am having an issue with a section where the left div is fixed and the right div is scrollable. However, the content of the right div scrolls even before the scroll top reaches the section. My goal is for the right div to scroll only when it reaches the t ...

Passing the value of each table row using Ajax

On my webpage, I have a list of orders displayed. I'm facing an issue where the value of each row in the table is not being passed correctly to my controller and database when a user clicks on a button - it always shows null. Can someone please assist ...

Registering dynamic modules within a nested module structure - Vuex

As stated in the Vuex documentation, a nested module can be dynamically registered like this: store.registerModule(['nested', 'myModule'], { // ... }) To access this state, you would use store.state.nested.myModule My question is h ...

How can I trigger the rendering of a component by clicking a button in a separate component?

I am currently facing a challenge in rendering a component with an "Edit" button that is nested within the component. I attempted to use conditional rendering in my code, but unfortunately, I am struggling to make it work as expected. Does anyone have any ...

Hide jQuery dropdown when mouse moves away

I am working on designing a navigation bar with dropdown functionality. Is there a way to hide the dropdown menu when the mouse pointer leaves both the navbar menu and the dropdown itself? I have tried using hover, mouseenter, and mouseleave but due to my ...

Steps to retrieve data (token) from developer tools and incorporate it into a fetch Post request

Is there a simple way to extract data using dev tools and insert it into a fetch request? I am trying to make a POST request through the console, but I am struggling to correctly copy a token. I attempted to use querySelector but instead of finding the t ...

Changing the time zone of a browser using JavaScript or jQuery

After researching numerous discussions on the topic, it appears that changing the browser's timezone programmatically is not possible. Although the moment-timezone.js library allows us to set timezone for its objects, it does not affect the browser&ap ...

Navigating on Blogger can be a tricky task when it comes to searching and

I recently added a Table to my blogger post, along with an input form for readers to easily search data. After finding the code on W3Schools (link here), I implemented it successfully. However, I am looking to make some improvements. Here is my question: ...

Efficiently Extracting Data from an Array of Objects Using JQuery

What is the best method to extract information from the array below? How can I retrieve data categorized by specific categories? Is there a way to access only the key values? How do I retrieve just the data values? var main = [{ "key": "all", "dat ...