Having trouble clearing the interval after setting it?

I developed a slideshow script called function slide(). The intention is for this function to begin when the 'play' button is clicked and pause when the 'pause' button is clicked. I implemented setinterval and it functions properly, however, clearinterval does not seem to be working as expected. Can you pinpoint what mistake I might be making here?

<div id='play' onclick='play()'><img src='image1/fleche.png'></div>
<div id='pause' onclick='stop()'><img src='image1/break.png'></div>
function play(){
    var test = setInterval(slide,500);}
function stop(){
    clearInterval(test);}

Answer №1

Here's a great example of how to implement the Revealing module pattern:

var mySlideShow = (function () {
    var intervalHolder;

    //this function is only accessible within the closure
    var slide = function(){
          //what happens in each slide?
    }

    function play(){
      intervalHolder = setInterval(slide, 500);
    }

    function stop(){
           clearInterval(intervalHolder);
     }

    return{
      play: play,
      stop: stop
    };
})();

To use it, just do this:

<div id='play' onclick='mySlideShow.play()'><img src='image1/fleche.png'></div>
<div id='pause' onclick='mySlideShow.stop()'><img src='image1/break.png'></div>

Some advantages of this approach include:

  • Avoids cluttering the global scope with variables
  • The Revealing Module Pattern ensures consistent syntax in our scripts and makes it clear which functions and variables can be accessed publicly at the end of the module, enhancing readability.

Answer №2

The reason why the code is not functioning properly is because the variable "test" is not defined within the stop function. To correct this, you can declare the "test" variable as global scope by modifying your code like so:

var test = null;

function start(){
    test = setInterval(slide, 500);
}
function end(){
    clearInterval(test);
}

Answer №3

The issue you are facing is due to the fact that the variable test is declared within the function play(), making it only accessible within that function scope. To solve this, you need to declare it outside of the function:

var test;
function play(){
    test = setInterval(function(){
console.log("hello")
},500);
}
function stop(){
    clearInterval(test);
}
<button onclick="play()">play</button>
<button onclick="stop()">stop</button>

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 is the speed difference between calling functions from require's cache in Node.js and functions in the global scope?

Let's imagine a scenario where we have two files: external.js and main.js. // external.js //create a print function that is accessible globally module.exports.print = function(text) { console.log(text) } Now let's take a look at main.js: ...

What is the best way to describe duplicate keys within a JSON array?

I have created a specialized program to extract Dungeons and Dragons data from JSON files. While the main functionality is complete, I am struggling with defining unique keys for multiple attack options without manually assigning individual identifiers. H ...

Server Sent Events not being received by client from Express.js server

My Next.js (React) client is set up to receive Server-Sent Events from my Node.js/Express.js server, but it seems like it's not receiving any messages for some unknown reason. While the open and error events of EventSource are functioning correctly, ...

Guide to implementing a variable delay or sleep function in JQuery within a for loop

I've noticed that many people have asked similar questions, but none of the solutions provided seem to work in my specific case. My goal is to incorporate a delay within a for loop with varying time lengths. These time lengths are retrieved from an a ...

Slideshow: I hope the Radio Button triggers the appearance of the next item in the rotation

I need to implement a carousel that displays the next item (Id="item2") when a specific radio button (Id="item1") is selected by default and another radio button (Id="item2") is pressed. Ideally, I would like to achieve this ...

How can you determine if a mouseover event is triggered by a touch on a touchscreen device?

Touchscreen touches on modern browsers trigger mouseover events, sometimes causing unwanted behavior when touch and mouse actions are meant to be separate. Is there a way to differentiate between a "real" mouseover event from a moving cursor and one trigg ...

The issue of the highlighted row not disappearing persists even after clicking on the adjacent table row

When selecting the gear icon for the menu option in a table row, I would like the background to turn yellow. I attempted the following code to highlight the table row: var view = Core.view.Menu.create({ model: model, menuContext: { ibmm: ibmm }, ...

Having some success with AngularJs autocomplete feature

Currently working on a small search application that utilizes Elasticsearch and AngularJS. I have made progress in implementing autocomplete functionality using the AngularJS Bootstrap typeahead feature. However, I am encountering difficulties in displayin ...

When attempting to import and utilize global state in a component, the error message "Cannot iterate over null object"

I am in the process of setting up a global state to keep track of various properties that I need to pass down to multiple components. const initialState = { username: '', selectedCategory: null, categoriesList: [], createdTaskTopi ...

How can I sort by the complete timestamp when using the Antd table for dates?

I have an item in my possession. const data: Item[] = [ { key: 1, name: 'John Brown', date: moment('10-10-2019').format('L'), address: 'New York No. 1 Lake Park', }, { ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...

Experiencing a problem with my JavaScript code in Node.js due to an asynchronous issue arising when using a timeout

My goal with this code is to retrieve JSON questions and present them to the user through the terminal. The user has 5 seconds to respond to each question before the next one appears. However, I encountered an issue where the next question times out automa ...

Harness the power of React Material-UI with pure javascript styling

I am currently attempting to implement Material-UI in pure javascript without the use of babel, modules, jsx, or similar tools. <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8 ...

Leveraging the Wikia API

I've been attempting to utilize the X-men API on Wikia in order to gather the name and image of each character for use in a single page application using JavaScript. You can find the link to the wiki page here: Despite my efforts, I am struggling to ...

Display a custom AngularJS directive on content loaded through $http request

I'm facing a dilemma. I have created a directive app.directive('a', function() { return { restrict: 'E', link: function(scope, elem, attrs) { elem.on('click', function(e){ ...

Issue with Mongoose: Create operations are not functioning properly right after performing Delete operations

I need to refresh my collection by deleting all existing documents and then repopulating them with new data from an API call. But when I try running the delete operations first, no new documents are created. Below is a simplified version of my controller ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

Parsing nested JSON files to present data on a webpage

I have a JSON file containing Reddit post titles and their respective scores: { "'JavaFX Simple Inventory Management App - Open source'": 39, "'Creating Formula Dependency Maps from Excel Spreadsheets'": 5, "'CVE-2017-5645 ...

Vue event emissions are not triggered or detected

This is the functionality of the Child Component: registerUser() { if (this.$refs.form.validate()) { this.$emit('showLoader', true); // Triggers this.$fireAuth .createUserWithEmailAndPassword(this.email, this.password) .the ...

JavaScript loop through an array of objects

Is there a way to loop through and retrieve all of the addresses? const name = { john: [ { age: 21, address: 'LA', } ], sam: [ { age: 26, address: 'California' } ] } I have tried using th ...