Bring the stopwatch to life during each request

Recently, I decided to dive into the world of Ractive.js. My latest project involves creating a stop watch that continues running even if I navigate to another page. However, I've encountered an issue where the stopwatch disappears when I return to the original page after clicking elsewhere. Any thoughts on what my next steps should be?

Below are the snippets from my attempts:

Within my view:

<div class="modal-footer">
    <div class="form-group">
        <div class="pull-left">
            Stopwatch: {{#stopWatch}} {{hours}} h: {{minutes}} m: {{seconds}} s{{/stopWatch}}
        </div>
        <button id="btnStart" class="btn btn-primary" type="button" on-click="startStopWatch">Start</button>
        <button id="btnReset" class="btn btn-secondary" type="button" on-click="startStopWatch">Reset</button>
    </div>
    <label class="pull-left stopWatch">  Time Spent:</label>
</div>

My startStopWatch function:

function startStopWatch(ev, cfg) {
    var rjs = this || cfg.rjs;
    var $btn = $(ev.node);
    var btnText = $btn.text();
    var sg;

    if (btnText === 'Start') {
        $btn.html('Stop');
        sg = new cmnDt.stopWatch();
        sg.start(rjs, sg);
    } else if (btnText === 'Stop'){
        $btn.html('Start');
        sg = ev.context.sw;
        sg.stop(rjs, sg);
    }

    if (btnText === 'Reset' && ev.context.sw) {
        sg = ev.context.sw;
        sg.reset(rjs, sg);
        $('#btnStart').html('Start');
    }
}

My stopWatch function:

function stopWatch() {

var currentSeconds = 0;
var currentMinutes = 0;
var currentHours = 0;
var timer;

function start(rjs, sw) {
    printTime(rjs, sw);
    timer = setInterval(function () {
        getTime();
        printTime(rjs, sw);
    }, 1000);
}

function getTime(rjs) {
    currentSeconds = currentSeconds + 1;
    if (currentSeconds === 60) {
        currentMinutes += Math.round((currentSeconds) / 60);
        currentSeconds = 0;
    } else if (currentSeconds === 60 && currentMinutes === 60) {
        currentMinutes = 0;
        currentSeconds = 0;
        currentHours += 1;
    }
}

function printTime(rjs, sw) { 
    rjs.set({'sw': sw, 'stopWatch.seconds': currentSeconds, 
        'stopWatch.minutes': currentMinutes, 'stopWatch.hours': currentHours});
}

function stop(rjs, sw) {
    clearInterval(timer);
    printTime(rjs, sw);
    $('.stopWatch').text(' Time Spent: ' + currentMinutes + ' m : ' + currentSeconds + ' s.');
}

function reset(rjs, sw) {
    clearInterval(timer);
    currentSeconds = 0;
    currentMinutes = 0;
    currentHours = 0;
    printTime(rjs, sw);
}

return {
    start: start,
    stop: stop,
    reset: reset
};
}

Answer №1

When you revisit the website, your entire script starts from scratch. To ensure that the stopwatch retains its current value and timestamp even after leaving the site, you must save this information permanently.

You have two options for achieving this: utilizing local storage or using cookies.

In ractive, the recommended approach for implementing local storage is demonstrated in this example:

If you create functions like saveToStorage() and initFromStorage(), your stopwatch will accurately display the elapsed time when you return to the site. It's important to note that the stopwatch doesn't continue running in the background but rather initializes based on the last recorded moment. This means it won't trigger events while you are on another webpage.


Updated on 15th March '16

Here's a functional stopwatch example in this fiddle:

https://jsfiddle.net/cw67L17e/2/

I started making changes to your code initially, but eventually decided to start fresh. While I haven't delved deep into ractivejs specifics due to time constraints, I believe studying this example can offer new insights and ideas. Check out the instructions provided on the right side of the fiddle for guidance.

Notes:

  • For simple time measurement purposes, you don't necessarily need a traditional "stopwatch". Storing timestamps suffices, as depicted by the prepareToLeave() and resume() methods.
  • To simplify handling of time units (seconds, minutes, etc.), focus on managing timestamps and converting them as needed, similar to the millisToHMS() function.
  • Explore the usage of localStorage.setItem() and localStorage.getItem() for storing and retrieving data.
  • To automate processes, consider calling resume() upon document readiness or load (document.ondomcontentready). Adapt this logic according to ractivejs conventions.

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

Ways to direct to dashboard if a user is logged in using AngularJS

As a newcomer to AngularJS, I am facing an issue with redirecting my page to the dashboard once the user has logged in. I receive an access token after login, which I save in cookies. Despite trying solutions from Stack Overflow, I have not been able to re ...

Position a div at the current mouse coordinates using Jquery

I am looking to constantly have a div follow my mouse cursor in order to display tool-tips. Below is the code snippet I'm using, but it's throwing an error: "Cannot read property 'pageX' of undefined" My question is why is pageX comin ...

Is it feasible to dynamically incorporate various versions of Bootstrap within the head tag?

The CMS I'm currently working with has a strict dependency on a specific version of Bootstrap. However, there are features from Bootstrap 3.3.6 that I need based on the page being loaded in the browser. I initially considered using JavaScript or jQue ...

Can you explain the significance of the '#' symbol within the input tag?

I was reading an article about Angular 2 and came across a code snippet that uses <input type='text' #hobby>. This "#" symbol is being used to extract the value typed into the textbox without using ngModal. I am confused about what exactly ...

"Step-by-Step Guide on Displaying Icons from One Folder to Another Page via a Link

I have a query regarding displaying icons (images). The icons are stored in the "img/icons" path. However, when I try to display them on a different page with the link "xxx/xxx/xxx/xxx", the icons do not show up. They only appear with the link "xxx/xxx" be ...

AngularJS - Refreshing Controller when Route Changes

Scenario app.controller('headerController', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.data = $routeParams; }]); app.config(['$routeProvider', function ($routeProvider) { ...

The webpage has finished loading, but capybara is still unable to pass the test

During my automation process, I am checking for the completion of document.readyState === 'complete' and also monitoring a local variable known as window.renderComplete (which indicates when the server has finished rendering the page). However, ...

The issue lies with the Cookies.get function, as the Typescript narrowing feature does not

Struggling with types in TypeScript while trying to parse a cookie item using js-cookie: // the item 'number' contains a javascript number (ex:5) let n:number if(typeof Cookies.get('number')!== 'undefined'){ n = JSON.pars ...

Differences between HTML server control and ASP.NET web controlsHTML server

When attempting to trigger a javascript function upon clicking a server control button, I encountered an issue. Using an html button control with the runat="server" attribute allowed me to successfully call the function. However, when employing an ASP.net ...

Extracting the URL of the @font-face declaration in CSS with the use of JavaScript

Currently, my CSS file contains numerous @font-face tags. Each tag specifies a unique font-family and src URL. @font-face{ font-family: Garamond; src: url('ePrintFonts/pcl_91545.ttf'); } @font-face{ font-family: C ...

Div that stays in place exclusively for mobile devices

At the top, there are two divisions and on a cellphone device, the second one is meant to become fixed after the user scrolls past it. To see an example of what I am trying to achieve, check out this link: https://jsfiddle.net/livibetter/HV9HM/ Specifica ...

Using the syntax ['] to access dynamic properties in Typescript

class Bar{ dynamicProperty: string; } I am curious about the behavior when accessing dynamic object properties. I came across an interesting approach in one of the answers provided here: let barObj: Bar = someObj['dynamicProperty']; However, ...

The reason why JavaScript condenses two or more spaces into just one space

After encountering a problem with my HTML/JS/Angular script, I created a simple demo to illustrate the issue. Although I have found a solution, I still wanted to seek advice from experts. <body ng-app> <div ng-controller='abc'> ...

Encountering the "Variable is not defined" error even when the variable has been previously defined. Currently working with EJS and Node

38| <h2 class="card-activity"> 39| <!-- Display Activity --> >> 40| <%= data.activity %> 41| </h2> 42| <div class="card-info"> 43| ...

Attempting to transfer information from a JSON file to a Netflix-inspired platform

Images I am currently working on integrating data from my json file export const products = [ { name: 'iPhone 11', image: '/assets/images (7).jpeg', time: '1 hour 14mins', age: '+16&apo ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

Is it possible to choose multiple tags using getElementsByTagName?

My website includes a javascript snippet that allows visitors to increase the font size of all paragraphs using the following javascript function: function increaseFontSize() { var paragraphs = document.getElementsByTagName('p'); fo ...

React component causing issues with API call triggered on each keystroke due to a problem with the component lifecycle

Scenario When my React component mounts, I start with an empty array for albums in my state. Objective With each input in my input field, I trigger an API call that fetches a list of albums based on the input. I need to add these albums to the array with ...

Unable to save array in global variable using Ajax, constantly receiving undefined

I'm attempting to store an array obtained from an ajax call in a global variable so that I can access it later, but I keep encountering an undefined error. <script> var items = []; function add(value){ items.push(value); ...

Combining two forms into one PHP page, but intending to submit only a single form

I'm facing an issue on my page where I have both a sign-in and a sign-up form. Whenever I click on either the sign-in or sign-up button, it always ends up submitting the sign-up form. What am I doing wrong? Here's the PHP code snippet: if($_SE ...