What is the proper way to halt a setInterval timer in javaScript by utilizing an eventListener?

I'm working on developing a pomodoro timer similar to the one found on this website TomatoTimer

However, I'm uncertain if my current approach is the most effective.

This is the function I have created:

function setTimer(minutes = "25") {
  let duration = minutes * 60 * 1000;
  let seconds = "00";
  let countdown = document.getElementById("timer");

  seconds = parseInt(seconds);
  minutes = parseInt(minutes);

  setInterval(() => {
    if (seconds === 0 && minutes > 0) {
      seconds = 60;
      minutes = minutes - 1;
      countdown.innerText = `${minutes}:${seconds}`;
    }
    if (seconds != 0) {
      seconds = seconds - 1;
    }

    if (seconds.toString().length === 1 && minutes.toString().length === 1) {
      countdown.innerText = `0${minutes}:0${seconds}`;
    } else if (minutes.toString().length === 1) {
      countdown.innerText = `0${minutes}:${seconds}`;
    } else if (seconds.toString().length === 1) {
      countdown.innerText = `${minutes}:0${seconds}`;
    } else {
      countdown.innerText = `${minutes}:${seconds}`;
    }

    duration = duration - 10000;
  }, 1000);
}

The reason why minutes and seconds are stored as strings is because I want the timer output in the format (01:05), and using numbers causes the "00" to be displayed as "0". The formatting aspect from the third "if" statement onwards is mainly for aesthetics and can be disregarded.

After defining this function, I attached an event listener to a button to initiate it successfully.

However, the challenge lies in halting the timer function once it's running.

My primary goal is simply to terminate the execution of the function without retaining the previous time settings. Adjusting that functionality will come later.

I've experimented with different solutions, such as utilizing the clearInterval method, but encountered difficulties when trying to call the function back through the eventListener after storing the interval in a variable.

Here are some questions I have:

  • Would it be more advisable to create the interval outside the function?
  • Is "setInterval" the optimal choice for this scenario?
  • Can the timer be stopped using the existing function setup?

To gain a comprehensive understanding of my project and progress thus far, feel free to review all my code on codepen.

Answer №1

An effective approach is to monitor the remaining time of the Timer until it reaches 00:00. When pausing the Timer, simply use clearInterval. To resume, call setInterval again, using the remaining time as an input.

To address the issue of retaining the interval reference, consider returning it from your setTimer function. For better organization, you could create a Timer class that handles the timer’s "state" and offers methods for interaction (such as pause(), stop(), resume(), reset()).

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

Attempting to transfer a JavaScript array to a PHP script for value printing proves unsuccessful

I am trying to send a JavaScript array to PHP in order to print the values, but it seems like it's not working as expected. Can someone help identify where I might be making a mistake? JavaScript $('#Enviar0').click(function() { var bu ...

The navigation icon on my website refuses to close

Hey there, I'm having some trouble creating a side navigation menu. The issue I am facing is that the menu opens without any problem, but then I can't seem to figure out how to close it using a second "onclick()" function. If you could take a lo ...

Steps to show a message on screen for a duration of 3 seconds using JavaScript

setTimeout(function(){ document.getElementById("alarmmsg").innerHTML=msg; },3000); The code above is successfully displaying the message but it's not going off the screen as expected. What might be causing this issue? ...

XState: linking together multiple promises seamlessly without needing intermediate states

After reading the Invoking Multiple Services section, it seems that despite being able to invoke multiple promises, they appear to be triggered without waiting for the previous one to complete in my own tests. // ... invoke: [ { id: 'service1' ...

Strategies for positioning identical Highcharts series next to one another

I am currently utilizing highcharts to create column charts. My column chart consists of multiple series, structured like this: Here is the code I am working with: $(function () { var chart; $(document).ready(function() { ...

Angular.js page failing to reflect changes following Firebase request completion

myApp.controller('RegistrationController', ['$scope', function($scope) { var auth = firebase.database().ref(); // console.log("auth::"+auth); $scope.login = function() { $scope.message = "Welcome " + $scope.user.ema ...

Making an Ajax request from within an iframe using the easyXDM framework

I am currently utilizing easyXDM for enhancing the communication between a website and a shopping cart embedded within an iframe on my domain. Whenever a user adds an item to the shopping cart, I utilize easyXDM.Rpc to transmit the item details to the ifra ...

Invoke a directive's function on a page by utilizing ng-click in AngularJS

Is there a way to call a function from a directive in an HTML page like index using ng-click? Below is the code for my directive: $scope.moreText = function() { $(".showMore").append(lastPart); }; html: <a ng ...

Arranging hierarchical data in JavaScript

After populating the hierarchy data, it is structured as follows: Here is a screenshot: I am looking to sort this data. Currently, I have a flat data object for rendering purposes. For example, my rendering object looks like this: renderedobjects=[ {1,. ...

Avoid transitioning to a different page using Vue-router

I have recently ventured into the world of Vue.js and my current project involves fetching data from an API, implementing pagination, and creating a detailed view for each post upon clicking. I have successfully implemented the pagination feature, however, ...

Modify an element upon clicking the mouse on an image

I am looking to dynamically change the paragraph element with className="details" to an editable input field when a user clicks on the image with className="edit-icon" within the same grid container. How can I achieve this functionality ...

How to activate a window that's been minimized in Chrome

I am experiencing an issue with a button that is supposed to open a new window as a popup below the parent page. It works correctly in IE and Firefox, but in Chrome, the popup appears on top of the parent window. Can someone please provide a solution? Fo ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...

Display a list of dates within a specified range using the ng

Utilizing the ng-repeat directive to connect data with a filter for name search: <div ng-repeat='myoldrecs in myoldrec | filter:q as results '>......</div> $scope.myoldrec = [{name:ccc,date:13-02-2016},{name:ddd,date:14-02-2016}]; &l ...

Selenium 'execute_script' unable to locate element using CSS selector, despite success in devtools console with querySelector

When loading the page on Chrome manually and running a querySelector function in the console, the correct element is returned. However, when using driver.execute_script with the same querySelector function, it returns None. from selenium import webdriver f ...

Customizing next.js _error page with i18n localization

Looking to create a customized error page for my Next.js project. I've been using the getServerSideProps method to localize my other pages, but I'm running into issues with translating strings on the _error page. I attempted to use the getStaticP ...

Using HTML5 chunks and web workers will not involve any uploading of files

I encountered an issue while working with html5 slice and webworker. It seems that when I try to upload a file using the uploadFile function, nothing is happening and the file is not being uploaded. <html> <head> <title>Uploa ...

Tips for implementing a JavaScript Material Design framework in ReScript code?

I am attempting to integrate the material-ui library into a Rescript/React application. The code snippet below demonstrates how to display a button: @module("@material-ui/core/Button") external button: string = "default" @react.compone ...

Callbacks in Laika tests go untriggered

Meteor.collection.insert() allows for the use of a callback as one of its arguments. To demonstrate, you can start a new Meteor project and execute the following code in the browser's console. my_collection = new Meteor.Collection("myCollection"); my ...

Creating new components within A-frame

I've been attempting to implement the bubble function into my scene to generate a sphere, but unfortunately nothing is showing up. Even when I try creating a sphere without using the bubble function, it still doesn't appear in the scene. func ...