JS: When the 'less than' operator falls short

I am facing an issue with a script that sends an AJAX request every 10 seconds (technically 11) to the user. I have created a simple countdown from 10 to 0 that repeats continuously.

The countit function is triggered after each AJAX request to reset the countdown.

Below is the code snippet:

function countit() {
  var count = 10;
  loading = setInterval(function() {
    $(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
    count--;
    if (count <= 0) {
      clearInterval(loading);
    }

  }, 1000);
}

Everything works as expected, except for when a user leaves and returns to the page, the countdown goes into negative numbers and does not stop. It can be seen in this image:

https://i.sstatic.net/8K0sH.png

I am unsure if this is an issue with the code or JavaScript itself, but the counter behaves unexpectedly when the user remains on the page.

Answer №1

According to Ibrahim & Chris:

To ensure the variable is not global, remember to add "var" in front of Interval.

function countit() {
    var count = 10;
    var loading = setInterval(function() {
        $(box).val("Will automatically check in " + count + "second(s), please DO NOT refresh the page yourself.");
        count--;
        if (count <= 0) {
            clearInterval(loading);
        }
    }, 1000);
}

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

Is there a way to include a button at the top of the Notiflix.Loading() overlay for closing or stopping it?

I've integrated the "notiflix" library into my project, and I'm currently using notiflix.loading.pulse() for a lengthy process. While this works perfectly fine, I would like to add a button (for closing/stopping the process) on top of the loading ...

Updating Angular 8 Component and invoking ngOninit

Within my main component, I have 2 nested components. Each of these components contain forms with input fields and span elements. Users can edit the form by clicking on an edit button, or cancel the editing process using a cancel button. However, I need to ...

In Node.js, it is essential to use req.session.save() to ensure that sessions are properly saved

While developing a website with Node.js, Express, and Redis for session management, I noticed an issue where my session variable (isLoggedIn) wasn't being saved after refreshing the page. Strangely, calling req.session.save() after setting the variabl ...

Navigating the parent-child hierarchy in Three.js

Two cubes were created with specific dimensions. The first cube had a width of 2083, height of 1987, and depth of 0. The second cube had a height of 40, width of 80, and depth of 0. The second cube was then positioned inside the first cube as its child wit ...

Fine-tuning Table Filter Javascript

I need help modifying some JavaScript code that currently searches for user input in the first column of a table and hides rows that do not contain that text. I want to update it so that it searches both columns 1 and 2: HTML: <input type="text" id="m ...

Tips for utilizing the nth-child selector to exclude hidden divs

I am facing an issue with displaying random blocks in rows. Each time a block falls into a new row, I want it to have a different style. However, when the user clicks on a button to hide certain blocks using display:none, the problem arises because the nth ...

After compiling, global variables in Vue.js 2 + Typescript may lose their values

I am currently working on a Vue.js 2 project that uses Typescript. I have declared two variables in the main.ts file that I need to access globally throughout my project: // ... Vue.prototype.$http = http; // This library is imported from another file and ...

Attempting to incorporate Google charts into a div using jQuery's load function

Trying to incorporate a basic Google chart using jQuery .load functionality to transfer the chart into another webpage with a specific containing DIV: <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi">< ...

Is there a way to make the React component automatically refresh upon clicking the search button?

Just starting out with React and JavaScript, I decided to experiment with accessing a public API. Here is the function I created: import { useState } from "react"; import CountrySWR from "./CountrySWR"; export default function SearchFo ...

A guide on extracting data from an uploaded JSON file in a React and Next.js application

Users have the ability to upload a JSON file by clicking on the button provided (shown below). https://i.sstatic.net/jndOd.png Once the JSON file is uploaded, the content is stored into a variable or a state. let fileRef = useRef(); const uploadHandle ...

Guide on how to capture tweets from particular Twitter profiles

I'm currently experimenting with the twitter npm package to stream tweets from specific accounts, but I'm facing some challenges. After reviewing the Twitter API documentation, I must admit that I am a bit perplexed. To fetch details about a pa ...

Having trouble with Webpack dynamic import not returning files in ReactJS? Here's how to fix it

Struggling with importing and using images in Reactjs? I've imported all images from a folder but it's not returning an array with links. Take a look. function importAll(r) { return r.keys().map(r); } const images = importAll(requi ...

Using Vue js to Specify the Type of a Prop

I am currently working on a Vue.js component that requires a prop named idFieldType The goal is to only allow this prop to accept values of type Number or String To achieve this, I implemented the following code: idFieldType: { Type: Function, d ...

Incorporate the variables specified in the parent PHP file into the PHP code being received through

I am currently working on a project that involves enabling a user to view his profile upon login. However, I am aiming to have the dashboard load all other profile pages through ajax, such as the view profile and edit profile pages. My progress so far inc ...

Refine the Crossfilter dimension according to the specified date range

What is the proper way to filter a date range using Crossfilter? The code above does not seem to yield any results, but I am certain that there are records within that specified time period. Var myDimension = CrossFilterObj.dimension(function(d) { retur ...

Ways to verify if a string is a number without using isNaN and with specified criteria

I am trying to determine if a string represents a valid number without relying on the isNaN function. The reason for this is that I need to be able to accept the ',' character, which isNaN ignores. Additionally, I do not want to allow negative nu ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

steps for making an AJAX request to a Laravel controller

I am currently working on a page that fetches data from a Laravel controller. On this page, there is a button that triggers a jQuery function. The interesting part is that the button's value contains a phone number, and I need to send an SMS to that p ...

efforts to activate a "click" with the enter key are unsuccessful

I'm attempting to enhance user experience on my site by triggering the onclick event of a button when the enter key is pressed. I've tried various methods below, but all seem to have the same issue. Here is my HTML (using Pug): input#userIntere ...