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

What is the process of transferring JavaScript code to an HTML file using webpack?

I am looking to display an HTML file with embedded CSS, fonts, and JS (not linked but the content is inside). I have the CSS and fonts sorted out, but I am struggling to find a solution for the JavaScript. My project is based on Node.js. ...

Validation is performed on the Bootstrap modal form, ensuring that the modal is only loaded after the

In order to provide a better understanding of my website's file structure, I would like to give an overview. The index.php file dynamically adds many pages to my website. Here is the code from index.php: <?php include ('pages/tillBody.php ...

The Vue.js modal is unable to resize below the width of its containing element

My challenge is to implement the Vue.js modal example in a larger size. I adjusted the "modal-container" class to be 500px wide, with 30px padding and a max-width of 80%. However, I'm facing an issue where the "modal-mask" class, containing the contai ...

Having trouble passing an array from PHP to JavaScript

I'm facing an issue with the following code snippet: <?php $result = array(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $result[] = sprintf("{lat: %s, lng: %s}",$row['lat'],$row['lng']);} ?> <?php $resultAM = joi ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

AngularJS dynamically creates an HTML template that includes an `ng-click` attribute calling a function with an argument

Struggling to create an HTML template using an AngularJS directive, the issue arises when trying to pass an object into a function within one of the generated elements. Here is the directive code in question: app.directive('listObject', function ...

Error in Angular form validation: Attempting to access property 'name' of an undefined value

Recently, I encountered an issue with my form while implementing Angular validation. The goal was to ensure that the input fields were not left blank by using an if statement. However, upon testing the form, I received the following error message: Cannot ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

Create a bespoke AngularJS directive for a customized Twitter Bootstrap modal

I am attempting to create a unique custom Twitter Bootstrap modal popup by utilizing AngularJS directives. However, I'm encountering an issue in determining how to control the popup from any controller. <!-- Uniquely modified Modal content --> ...

Ways to implement the tabIndex attribute in JSX

As per the guidelines provided in the react documentation, this code snippet is expected to function properly. <div tabIndex="0"></div> However, upon testing it myself, I encountered an issue where the input was not working as intended and ...

The error message "[Insecure URL]" was triggered at line 85 of angular.min.js in the AngularJS framework

Looking for some assistance with Angular as I have limited knowledge. It was working fine on localhost, but after upgrading from PHP5 to PHP7, I encountered this error: angular.min.js:85 Error: [$sce:insecurl] http://errors.angularjs.org/1.2.13/$sce/inse ...

Ways to automatically update property value in MongoDB once a particular date is reached

Is it feasible to schedule a future date for a document in MongoDB, such as 30 days from the current date, and then automatically update another property of the document when that future date arrives? For instance: creating an event document setting the ...

Is it possible to create an online game using JavaScript?

Hey there, I'm interested in creating a simple online game that can be played in the browser. My main question is this: if I want two players to compete against each other online, can I achieve this by using HTML for the front-end and JavaScript for t ...

Issue with retrieving date from MySQL column being a day behind in JavaScript (Node.js)

I currently have a Node.js server up and running as the API server for a service that I am developing for a company. The dates stored in the MySQL server that it connects to are related to event start times. Insertion of these dates is flawless, and when ...

"There seems to be an issue with the KeyListener function in

The error I'm encountering is: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null I'm unsure about what went wrong. The intention behind the code was to store the result of the selected radio button into a ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...

Can someone help me figure out this lengthy React error coming from Material UI?

Issues encountered:X ERROR in ./src/Pages/Crypto_transactions.js 184:35-43 The export 'default' (imported as 'DataGrid') could not be found in '@material-ui/data-grid' (potential exports include: DATA_GRID_PROPTYPES, DEFAULT ...

Need a jQuery callback function in PHP that only retrieves the value without any redirection

Initially, I expected this task to be simple but it turns out my skills are a bit rusty. The snippet of javascript/jquery code that I am using is: $.get("plugin.php", {up_vote:surl}, function(data){ //alert(data); document.getElementById(&apo ...

Checking if a variable is true with jQuery

Check out this snippet of code: <main class="ok">My text</main> <script> $(document).ready(function() { if ( $('body').not('main.ok') ) { // or if ( Boolean ( $('main.ok') ) == false ) { ...

Error: React JS is unable to access the property 'path' because it is undefined

Currently, I am encountering an issue while setting the src of my image in React to this.props.file[0].path. The problem arises because this state has not been set yet, resulting in a TypeError: Cannot read property 'path' of undefined. To provid ...