Count up in Javascript starting from the page load and reset using ajax calls

Having some difficulty with resetting a counter in Javascript that I found on Stack Overflow. Here is the code for the counter:

var pageVisited = new Date(); // consider storing this data in a database, session, or at least a cookie

setInterval(function() {
    var timeOnSite = new Date() - pageVisited;

    var secondsTotal = timeOnSite / 1000;

    var seconds = Math.floor(secondsTotal);

    document.getElementById('time').innerHTML = seconds;
}, 1000);

I have tried the following based on suggestions from other posts:

function stopTime(){
  clearInterval(timeOnSite);
}

Unfortunately, this method restarts the counter but causes two counters to run simultaneously.

My goal is simply to reset the counter back to 0 and start again when the user clicks 'Update' (data update functionality is already working).

Any help or recommended resources would be greatly appreciated.

Thank you

Answer №1

In order to properly clear the interval, you must first assign it to a variable.

function myFunction() {
    var timeElapsed = new Date() - pageOpened;
    var secondsTotal = timeElapsed / 1000;
    var seconds = Math.floor(secondsTotal);

    document.getElementById('time').innerHTML = seconds;
}

var timerInterval = setInterval(myFunction, 4000);

To reset the interval, simply clear it using the assigned variable as shown below:

clearInterval(timerInterval);
timerInterval = setInterval(myFunction, 4000);

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

How many parameters are typically transmitted through URLs in a nodeJS environment?

Is there a way to identify the number of parameters included in a URL? What approach can I use to count the parameters sent through a URL in nodeJS? ...

Did you stumble upon an unexpected JavaScript redirection?

I am facing an issue with my form where pressing enter redirects the URL instead of adding an item to a list, while clicking the submit button works fine. I'm not sure what caused this sudden change in behavior. Here is the HTML code snippet: <fo ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

What are the steps to make standard calls from the main controller?

My website has date selection functionality on all pages, where API data is displayed based on the chosen date. However, I want the selected date to be consistent across all pages. Currently, I am using the code $scope.cb(moment().subtract(29, 'days&a ...

What is the best way to handle multiple promises when loading a state in Angular?

When loading the /home state, I need to retrieve all users from the database in order to customize the home controller and view based on the logged-in user. Currently, in the :resolve section of the state configuration, I am fetching all 'posts' ...

Determine the size of a JSON array in AngularJS

I have a JSON data set and I am attempting to calculate the length of an array called Infos: Here is my JSON structure: "Association": { "Items": [ { "AssocName": { "SurName": "BLOGGS", "Title" ...

How to efficiently use lunr in typescript?

The Definitely Typed repository demonstrates the importation in this manner: import * as lunr from 'lunr'; However, when attempting to use it in Stackblitz, it results in the following error: lunr is not a function Any ideas on how to resolve ...

Steps for setting up node-openalpr on a Windows 10 system

While attempting to install npm i node-openalpr, an error is occurring: When using request for node-pre-gyp https download, I encounter a node-pre-gyp warning and error message. The package.json for node-openalpr is not node-pre-gyp ready, as certain pr ...

Is it possible to use AJAX to submit a form and then redirect to a different webpage?

My website has a search feature that is present on all pages. I am currently working with jQuery/AJAX to gather the search input data, process it, and then display the results on a dedicated search results page. Below is the HTML code for the search secti ...

I encountered an issue when trying to import a React.js component in TypeScript. The .d.ts file was created by myself, but I received the error message "Module not found: Can't resolve 'xxx' in 'xxx'"

I included the TypeScript definition file for a component in my project: /// <reference types="react" /> declare namespace __ReactAvatarEditor { interface croppingRect { x: number, y: number, width: number, height: number } interf ...

Screen the embedded array depending on the criteria

Here is an example of an object I have: data = { "suites": [ { "status": "fail", "testcases": [ { "status": "pass" }, ...

In search of an improved scoring system for matching text with JavaScript

For many of my projects, I've relied on String Score to assist with sorting various lists such as names and countries. Currently, I am tackling a project where I need to match a term within a larger body of text, like an entire paragraph. Consider t ...

Modify iframe form action URL dynamically upon user visiting the URL with a specified parameter

Below you will find a code example: The page URL is: <html> <body> <h1>main page</h1> <iframe src="http://example2.com"> <form id="test" action="http://example3.com?id=1"> ... </form&g ...

What is the purpose of using the grouping operator in this particular line of code?

While exploring the express-session npm package source code, I came across this particular line: // retrieve the session ID from the cookie var cookieId = (req.sessionID = getcookie(req, name, secrets)); Do you think it's essentially the same as this ...

Automated pagination integrated with automatic refreshing of div every few seconds

I am currently working on setting up a datatable and I need it to be displayed on the monitor in such a way that it can refresh the div and automatically paginate to the next page. However, whenever the div is refreshed, the auto-pagination gets cancelle ...

Access and retrieve dynamically generated table row values with the use of AngularJS

Hi, I'm new to angularjs and I have a table where I need to dynamically add rows. I've got everything working with a bit of JQuery but I'm having trouble getting the value of dynamically created table rows. Here's my code, can someone p ...

Is it possible to update the useContext value within a child component so that all other child components can access the updated value?

Is there a way to set a default value (like null) in a parent context and then change that value in a child component so other children can access the updated value? For example, imagine we have an App.jsx file where a userContext is created and passed do ...

Invoke callback function to manage modal visibility

My project includes a modal for displaying a login/register form. The default behavior is that the modal opens when triggered by another component using the props show. This setup works perfectly when the modal is called by this specific component. Furthe ...

React context fails to refresh

I created a simple project that utilizes Context to store the page title, but I am experiencing an issue where the component is not being re-rendered after setting it. Main files: Context.js import React from 'react' const Context = React.cre ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...