What is the best way to cancel an interval within an immutable object?

I'm currently attempting to clear the interval within the slide.autoplay function in this particular JavaScript snippet.

I would like to incorporate another function into my constant, such as a slide.stop function.

slide = {
    init: () => {
        eraser.content()
        slide.autoplay()
    },
    next: () => {
        eraser.start()
        currentSlide < 1 ? currentSlide++ : currentSlide = 0
        eraser.content()
        eraser.end()
    },
    autoplay: () => setInterval(slide.next, 5000)
}

addEventListener( 'DOMContentLoaded', slide.init )
addEventListener( 'click', slide.stop )

By the way, I have been using functions within constants for some time now and find it suitable. However, I am unsure if it is considered good practice. What are your thoughts on this?

Answer №1

In order to successfully reset the interval, you must ensure it has been saved first:

slideshow = {
  timer: null,
  initialize: () => {
    canvas.display()
    slideshow.startAutoPlay()
  },
  moveForward: () => {
    canvas.begin()
    currentSlide < totalSlides ? currentSlide++ : currentSlide = 1
    canvas.display()
    canvas.complete()
  },
  startAutoPlay() {
    this.timer = setInterval(slideshow.moveForward, 4000)
  },

  pause() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}

Answer №2

One way to manage timing in JavaScript is by storing the id that is returned by the `setInterval` function.

const slideshow = {
    intervalId: null,
    play() {
        this.intervalId = setInterval(this.next, 1000);
    },
    next() {
        console.log("Moving to the next slide");
    },
    stop() {
        clearInterval(this.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

In JavaScript, alert a message once all images have been clicked

I'm encountering a small issue with my javascript code. I am developing a game for a school project where the objective is to click (remove) fish using a fishing rod. However, the game does not have an end condition set up, so players cannot win. Belo ...

Protractor map function fails to provide a defined output

When working with an application containing multiple widgets, each with its own title and content, I want to effectively map the elements of each widget for easier testing purposes. For instance, let's consider a page: this.widgets = element.all(by. ...

What is the best way to save request URLs in JavaScript while following the DRY principle?

Is there a standard practice in JavaScript for storing the URLs of endpoints used in AJAX applications? Would you, for instance, consider creating a "Service" class to encapsulate the URLs? ...

Display a dynamic animation once the user switches to the tab

When a user opens the page in a new tab in the background, CSS animations are triggered before they switch to the tab. Is there a method to display the CSS animation only after the user selects the tab? ...

Is it advisable to utilize jQuery's parseJSON/getJSON functions?

Upon examining the jQuery parseJSON function, I discovered that it essentially performs a basic regex validation: parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Remove leading/trailing white ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

The functionality of the Google API JavaScript client is sporadic, intermittently working and occasionally

Having an issue with the Google API JavaScript client that I can't seem to solve. Here's the script in my HTML file: <script src="https://apis.google.com/js/client.js?onload=init"></script> This is what my JavaScript code looks lik ...

What could be causing Express.js to return two responses from the server?

As a beginner in learning express.js and node.js, I am currently working on creating a basic server using the following code: const http = require('http'); const express = require('express'); const app = express(); ap ...

Iterating through elements to set the width of a container

I am currently working on a function that dynamically adjusts the width of an element using JavaScript. Here is my JavaScript code: <script> $('.progress-fill span').each(function(){ var percent = $(this).html(); if(per ...

Using express version 4.x to send an empty JSON object

I'm struggling with returning an object in JSON format using Express. What's confusing me is the following code snippet: class Greeting { Greeting(name) { this.name = name; } get name() { return name; } } app.get('/json/:na ...

Verify whether the element in the DOM is a checkbox

What is the method to determine whether a specific DOM element is a checkbox? Situation: In a collection of dynamically assigned textboxes and checkboxes, I am unable to differentiate between them based on their type. ...

How can I make sure addEventListener only responds to numbers and not images?

Currently, I am facing a dilemma with implementing a button that features an image on it and needs to be placed within another div. Despite successfully achieving this, I am struggling to comprehend the JavaScript code outlined in a tutorial I followed. Th ...

What is the best way to generate a loop that builds a full deck containing all 52 cards?

I am currently working on implementing a deck object in JavaScript, with two separate files - one for the card constructor and the other for the deck logic. My goal is to create a load function within the deck object that will populate the deck with 52 uni ...

submit the JSON formatted data to the server

I am attempting to extract data from a form and transmit it to a remote server: Below is the code snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> ...

Is there a way to alter the text color using JavaScript on the client side?

Is there a way to change the color of a list item in a ul based on whether it is a palindrome or not? Here is the JavaScript file I am working with: function isPalindrome(text){ return text == text.split('').reverse().join(''); } c ...

Obtain the identification numbers from the row within the table

I have a table displaying an email Inbox (see excerpt screenshot here). When the user clicks on a checkbox, I need to populate two dropdowns with the correct items. function fnHandleSelectCBClick(cb) { try { var tableRow = $(cb).parent().par ...

Javascript Rest for y moments

My website's JavaScript function uses AJAX to retrieve account information and open a modal for viewing and editing. Sometimes, the details don't update quickly enough in the database before the function collects them again, leading to discrepanc ...

The circles seem to be elusive, refusing to make an appearance on the forefront of the HTML webpage

My scatterplot circles appear to be behind the graph, and I can't figure out how to bring them to the front. Can anyone help me with this issue? Even though the inspection shows that the circles are there, they are not visible on the plot. scatterplo ...

Styling with CSS to position a div tag on top of a webpage

I have a calendar code inside a div and I want to display the calendar when clicking an anchor tag without sliding the entire div. Currently, it is displayed as: However, I want it to be displayed as shown in the next image: <a class="aastext"&g ...

Tips for obtaining the top 3 highest-value objects in a JavaScript array over all other elements

I am working with an array that contains objects, each with two properties: name and value. array = [ { name: 'name1', value: 0 }, { name: 'name2', value: 2 }, { name: 'name3', value: 4 }, { name: 'n ...