Is there a way to effectively incorporate window.clearInterval() into this javascript code to achieve the desired outcome

In my quest to create a pomodoro clock, I decided to experiment with window.setInterval() and its counterpart window.clearInterval before delving into actual coding. However, I've encountered an issue with getting window.clearInterval() to function as desired. Could someone please review my code snippet below and provide guidance on how to resolve this issue? Thank you in advance.

let startTime = 11;
let intervalID;

function countdown() {
  startTime--;
  $('h2').text(startTime);
}

if (startTime > 0) {
  intervalID = setInterval(countdown, 1000);
} else {
  clearInterval(intervalID);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>

Answer №1

When examining your code, the condition if (startTime > 0) is only evaluated once. To improve this functionality, consider implementing it in the following manner:

$(document).ready(function() {
    var startTime = 11;
    var intervalID;
    function downCounter() {
        startTime--;
        $('h2').text(startTime);
        if (startTime <= 0){
            clearInterval(intervalID);
        }
    }
    intervalID = setInterval(downCounter, 1000);    
});

Answer №2

The code inside the `if` statement is as follows:

if (startTime > 0)
  intervalID = setInterval(downCounter, 1000);
else
  clearInterval(intervalID);

In this scenario, the `else` block will never be executed.

This particular segment of code executes only once, before the timer commences, at a point where it is certain that `startTime` has a value greater than zero.

To resolve this issue, check the value of `startTime` within the handler function and clear the interval there if needed:

var startTime = 11;
var intervalID;

function downCounter() {
  startTime--;
  $('h2').text(startTime);
  
  if (startTime <= 0)
    clearInterval(intervalID);
}

intervalID = setInterval(downCounter, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>

Answer №3

Make sure to include the clearInterval within the downCounter function:

    function downCounter() {
      startTime--;
      $('h2').text(startTime);
      if (startTime <= 0 ) {
        clearInterval(intervalID);
      }    
    }

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

What methods does Enzyme have for determining the visibility of components?

I am facing an issue with a Checkbox component in my project. I have implemented a simple functionality to hide the checkbox by setting its opacity : 0 based on certain conditions within the containing component (MyCheckbox) MyCheckBox.js import React fr ...

removing a specific cookie from the browser's cookies using jQuery

This block of code displays a URL along with a delete image for removing a cookie. The add and display functions are working fine, but I'm stuck on how to implement the delete function. function backLinks(){ var pathname = window.location; va ...

Snippets of the webpage peeking through before the Fakeloader takes over

After implementing fakeloader to preload my content here, I have noticed that my site header often appears before the fakeloader preload animation completes. Is there a way to delay showing the content until the fakeloader is finished loading? Here is the ...

``The Art of Handling REST API with Express and Mongoose

Running Express on my application, I have a delete route set up as shown below: router.route('/lists/:id') .delete(function(req, res){ Entry.remove({ _id: req.params.id }, function(err, list){ if(err) ...

Stop music with one click, code in Javascript

I am encountering an issue with a set of 5 div boxes on my website. Each box is supposed to play a specific audio track when clicked, based on data attributes. However, I'm having trouble pausing the previous track when clicking on a new box, resultin ...

Having issues with React-router v4's this.props.history.push() not functioning as expected

I'm attempting to programmatically redirect using the this.props.history.push(..) method, but for some reason it's not working. Here is the routing setup: import { BrowserRouter as Router, Route } from 'react-router-dom'; <Route ...

Incorporating arguments within the context of a "for each" loop

I'm attempting to develop a straightforward script that converts RGB-16 colors to RGB-8. The script is functioning properly, but I'm having trouble converting it into a function that can handle two different palettes. Whenever I try using palette ...

Swapping out the default JavaScript random number generator for my custom JSON-based solution

I've been working on creating a D3 graph to display my data. After following a tutorial, I arrived at this particular piece of code: // 8. An array of objects of length N. Each object has key -> value pair, the key being "y" and the value is a r ...

The issue with the full postback in the updatepanel is triggered by utilizing JavaScript on the button's onclick event within

During my testing, I encountered an issue with buttons inside a repeater within an update panel. When adding asyncpostback triggers for the buttons using <Trigger></Trigger>, an error is generated indicating that the button could not be found. ...

Searching for a single cell within an HTML table

I've been on the hunt for a code that can search through a table and show just one cell. I tried creating my own, but finally stumbled upon one that seems to work perfectly, except for one hiccup. When the search bar is cleared, it displays the first ...

Discovering the optimum route within a 2D array given specific limitations using Dynamic Programming

Hey, I have a query related to dynamic programming (dp) that goes like this: Input: A 2D array of numbers Output: The maximum sum of a path from (0,0) to (n-1,n-1) with the following conditions: You can only move down and right i.e. from (A[i-1][j]) t ...

Achieving responsive masonry layout with Bootstrap 4

I'm attempting to implement the bootstrap 4 masonry effect on my website, but I'm facing issues with card responsiveness. The page is very basic without any special effects. While the page works well when resizing the browser window, it doesn&ap ...

Utilize jQuery to select the parent checkbox and mark it as checked

Currently, I am working on a JavaScript function that will automatically check the parent checkbox if a child checkbox is checked. I am implementing this using jQuery and here is my HTML code: <ul id="ulParent" style="margin: 0; padding: 0; list- ...

Determine the index of a specific character within a string using a "for of" loop

How can I obtain the position of a character in a string when it has been separated programmatically using a for...of loop? For instance, if I wish to display the position of each character in a string with the following loop: for (let c of myString) { ...

The hamburger icon seems to be frozen and unresponsive

I'm struggling to get my hamburger icon to reveal the navigation bar when clicked. The icon itself functions properly and adapts to different screen sizes, but the overlay remains stationary. Check out my code on JSFiddle! <html> <head> ...

What are the steps to showcase a webcam stream in GLSL by leveraging Three.js?

One method of displaying a webcam video using ThreeJS involves creating a video texture, as shown below: video = document.getElementById( 'video' ); const texture = new THREE.VideoTexture( video ); texture.colorSpace = THREE.SRGBColorSpace; const ...

Unresponsive JavaScript on specific element IDs

I'm experimenting with making three lines perform different animations: line 1 rotating 45deg and translating, line 2 becoming opaque, and line 3 rotating -45deg and translating. Check out my JS Fiddle here <a href="#"><div id="menu" onclic ...

What is the best way to set the sidebar height to 100% in Material-UI?

Trying to learn MUI and encountered a problem. I want the sidebar to cover the full height, I tried 100vh but it stops increasing when the table extends. Using 100% only covers the end of the list. Is there another way to solve this, or is it fine becaus ...

A guide to efficiently reusing parameter definitions in functions using JSDoc

Currently, I have HTTP handlers set up in my express application. I want to use JSDoc annotations to document these handlers in a reusable manner. Here is what I currently have: /** * * @param {functions.Request} req * @param {functions.Response} res ...

Middleware in Express.js Router

In the following code snippet, I am aiming to limit access to the 'restrictedRoutes' routes without proper authorization. However, I am encountering an issue where 'restrictedRoutes' is affecting all routes except for those within the & ...