The countdown value in Javascript is not being reset when clearInterval is called

Currently, I am working on implementing a swiper slider with a countdown feature that resets its value every time a slide change occurs. The countdown should restart when the next slide is displayed automatically. However, I have encountered an issue where clicking on the navigation dots results in a double countdown effect. It seems like the clearInterval function initiates another countdown without properly removing the previous countdowns from the thread execution.

var autoplay = 20000;
var swiper = new Swiper('.swiper-container', {
    pagination: '.swiper-pagination',
    paginationClickable: true,
    watchSlidesProgress: true,
    autoplay: 20000,
    onProgress: elipse
});

function elipse() {
    clearInterval(timer);
    var countdownNumberEl = document.getElementById('countdown-number');
    var countdown = 20;
    countdownNumberEl.textContent = countdown;
    var timer = setInterval(frame, 1000);
    function frame(){
        countdown = --countdown <= 0 ? 20 : countdown;
        countdownNumberEl.textContent = countdown;
    }
}

var swiperBullet = document.getElementsByClassName("swiper-pagination-bullet");
for (var i = 0; i < swiperBullet.length; i++) {
    swiperBullet[i].addEventListener('click', function () {
        elipse();
    });
}

I would appreciate any assistance in resolving this issue and understanding what is causing it.

Answer №1

Ensure that the variable timer is declared globally to maintain its value, as local variables reset each time a function is called. To prevent errors when trying to stop a non-existent timer, consider adding a clear conditional in your code:

var timer = false;
function ellipse() {
  if(timer !== false) {
    clearInterval(timer);
  }
  [...]
  timer = setInterval(frame, 1000);

Answer №2

It seems that in this scenario, the variable timer has not been declared and remains undefined.

function elipse() {
    //timer will be undefined or throw error that is not declared
    //so you are not clearing anything
    console.log(timer);
    clearInterval(timer);
    //stuff

    //this wil redaclare timer every time you enter the function and it will return different intervalID
    //so this will grow exponentially
    var timer = setInterval(function () {
        elipse()
    }, 1000);
}
elipse()

In order to rectify this issue, it is advised to declare timer outside of the scope for the function elipse. It does not need to be a global variable; just place it outside of the scope like so:

(function () {
  var timer;
  function elipse() {
      //only the first time will be undefined
      console.log(timer);
      clearInterval(timer);
      //just don't redeclared timer becouse it will be for this scope and it will create a new intervalID that you can't access
      timer = setInterval(function () {
          elipse()
      }, 1000);
  }
  elipse()
})();

P.S. clearInterval expects intervalID

The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to setInterval().

Additionally, the Return value of setInterval is a numeric, non-zero value

Therefore, having undefined as the value may not pose any significant issues

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

Dealing with event delegation on elements that are not nested

Working with Bootstrap group radio buttons where I need to implement event delegation. <div class="btn-group" role="group" aria-label="Basic radio toggle button group"> <input type="radio" class="btn- ...

One function is failing to execute properly due to multiple if conditions

Take a look at my JavaScript code below: function showLater1() { if ((vidos.currentTime >= 30) && (vidos.currentTime <= 34)) { lay.style.opacity = "1"; content.style.opacity = "0"; controls.style.opacity = "0"; ...

Ways to use the v-if directive to render conditionally based on a property, even if the object may be undefined

Keep in mind that the parent variable is a firebase reference that has already been defined. Using it like this works fine: v-if="parent['key'] == foo" However, when trying to access a child element like this: v-if="parent['key'].ch ...

Utilize Aframe to easily view and upload local gltf files

I've been working on a project to create a user-friendly panel for loading and viewing gltf models in real-time in A-frame. Here is the current workflow I am following: Using the input tag to load files from local storage. Using v-on-change to assi ...

What is the most efficient method for managing axios errors in Laravel and Vue.js?

Currently, I am developing spa web applications using Laravel as the backend and Vue.js as the frontend framework. For authentication with API, I am utilizing Laravel Passport, and for managing my application state, I am using Vuex. Initially, I created A ...

The display of temporary headers - Nodemailer - AJAX

I keep receiving a warning in the request header that says: Provisional headers are shown. I'm struggling to identify the root cause of this issue. This warning prevents the readyState from changing and my callbacks on the eventhandler onreadystatecha ...

Creating a Select component in React without relying on the Material-UI library involves customizing a dropdown

Is there a way to achieve a material UI style Select component without using the material UI library in my project? I'm interested in moving the label to the top left corner when the Select is focused. export default function App({...props}) { retu ...

The form features a "Select all" button alongside a series of checkboxes for multiple-choice options

I am facing difficulties trying to get the "Select all" and "Remove all" buttons to function properly within my form. Whenever I remove the "[]" (array) from the name attribute of the checkboxes, the JavaScript code works perfectly fine. However, since I n ...

What is the best way to retrieve local variables within a React function?

I keep encountering this issue where I get a TypeError saying that the property 'classList' cannot be read for an undefined value, and this error occurs even before the functions are executed. The specific line causing the error is slide[n].class ...

What could be causing my JavaScript loop to replace existing entries in my object?

Recently, I encountered an issue with an object being used in nodejs. Here is a snippet of the code: for(var i = 0; i < x.length; i++) { var sUser = x[i]; mUsers[sUser.userid] = CreateUser(sUser); ++mUsers.length; ...

Using THREE.js: Object3D Dimension Shrinkage

Is there a way to disable sizeAttenuation for an Object3D in THREE.js? I'm working on rendering a trajectory at a massive scale using arrow helpers to show the motion direction. I want the arrow heads to maintain their orientation without changing si ...

Displaying directory contents with JavaScript XHR

When I inquired whether javascript has the ability to list files on the server, the general response was that "javascript cannot access the server filesystem since it is a client-side scripting language". However, I believed this answer was only partially ...

Guide to dynamically add data to two columns

I have a challenge with organizing multiple inputs into rows with two columns each, ensuring that each input is appended to the appropriate side (50% for each column unless there's an odd number of inputs). Currently, the inputs are being added to se ...

Validating Linkedin URLs with JavaScript for Input Fields

I've created a basic form with an input field for a LinkedIn URL. Is there a way to validate that this field only accepts valid LinkedIn URLs? Thank you! ...

What is the best way to retrieve a specific value from a nested array that is within an array of objects

My goal is to extract a specific field value from a nested array within an object array. Using the map method, I attempted to achieve this but ended up with two empty arrays nested inside two empty objects. Though I am aware of this mistake, it indicates t ...

Verifying X-editable input in Laravel (Server-side)

I've successfully integrated x-editable into my webpage (). When I click on a field, it becomes editable inline, allowing me to make changes and submit them to a POST URI. Currently, I am sending three key-value pairs: array:3 [▼ "name" => "n ...

Deleting a specific element in React: Step-by-step guide

Having an issue with the handleDelete() method in DisplayList.JSX where it is deleting the first element instead of the selected element. How can this be resolved? Github Display.jsx import {DisplayList} from './DisplayList'; class Display e ...

challenges surrounding the use of getElementByTagName

Within my webpage, I have implemented two select elements, both containing multiple options. However, I am facing an issue where I can only access the options from the first select box using getElementByTagName("options"), and unable to retrieve the option ...

Invalid element type detected. A string was expected, but instead found undefined

Following a recent update of next-auth, an unexpected error has surfaced: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your compon ...

Is there a way to apply a setTimeout to a <div> element upon the first click, but not on subsequent clicks?

Check out the fiddle I've created: http://jsfiddle.net/dkarasinski/dj2nqy9c/1/ This is the basic code. I need assistance with a functionality where clicking on a black box opens a black background and then after 500ms a red box appears. I want the ...