Is there a way to stop a setInterval function that is running using a global variable?

I've been trying to figure out how to stop a running setInterval, but despite making changes based on various resources, I still can't seem to get it to stop.

Currently, I have implemented a Mutation Observer that detects a class change. Once this change occurs and two specific conditions are met (related to the presence of other classes), cursor tracking is triggered successfully.

My goal is to halt the setInterval when one of the required classes, '.run-preview', is removed. I have included an 'else if' statement for this purpose, where I attempt to clearInterval as desired. Upon testing, the 'else if' condition appears to be functioning correctly.

To achieve this functionality, I have defined a global variable 'intervalCursor = setInterval(move,1000/60);'. Subsequently, I use this variable in conjunction with 'clearInterval(intervalCursor);' to terminate the interval when necessary.

const runPreview = document.querySelector('.projects');

new MutationObserver((mutations) => {
  if (mutations[0].attributeName === 'class') {
    console.log('Project list class changed');
 
    if ($('html').hasClass('no-touchevents') && ($('.projects').hasClass('run-preview'))) {
    
        var mouseX=window.innerWidth/2,
            mouseY=window.innerHeight/2;
        var intervalCursor = setInterval(move,1000/60);
            
        var projectPreview = {
         el:$('.image-container'),
         x:window.innerWidth/2, 
         y:window.innerHeight/2, 
         w:300,
         h:300, 
         update:function() {
           l = this.x-this.w/2; 
           t = this.y-this.h/2; 
           this.el.css({ 
            'transform':
            'translate3d('+l+'px,'+t+'px, 0)' });
            //console.log("transform");
           }
        }
        
        $(window).mousemove (function(e){
          mouseX = e.clientX;
          mouseY = e.clientY;
          //console.log("mousemove");
        })
        
        
        function move(){
          projectPreview.x = lerp (projectPreview.x, mouseX, 0.1);
          projectPreview.y = lerp (projectPreview.y, mouseY, 0.1);
          projectPreview.update() 
          console.log("move");
        }
        
        function lerp (start, end, amt){
          return (1-amt)*start+amt*end
        }

    } else if (!$('.projects').hasClass('run-preview')) {
        clearInterval(intervalCursor);
        return;
        //$('#content-container').addClass('test');
    }
 
  }
})

.observe(runPreview, { attributes: true });

Is there something missing or incorrect in my setup?

Answer №1

Special thanks to Ouroborus for the invaluable assistance in solving this challenge. The key breakthrough came from creating a separate variable in parallel with the MutationObserver, which was then utilized to execute setInterval(move,1000/60); at a later stage. This approach enabled effective clearing and stopping of setInterval as needed.

var intervalCursor

const runPreview = document.querySelector('.projects');

new MutationObserver((mutations) => {
  if (mutations[0].attributeName === 'class') {
    console.log('Change detected in project list class');
 
    if ($('html').hasClass('no-touchevents') && ($('.projects').hasClass('run-preview'))) {
    
        var mouseX=window.innerWidth/2,
            mouseY=window.innerHeight/2;
            
        var projectPreview = {
         el:$('.image-container'),
         x:window.innerWidth/2, 
         y:window.innerHeight/2, 
         w:300,
         h:300, 
         update:function() {
           l = this.x-this.w/2; 
           t = this.y-this.h/2; 
           this.el.css({ 
            'transform':
            'translate3d('+l+'px,'+t+'px, 0)' });
            //console.log("transform");
           }
        }
        
        $(window).mousemove (function(e){
          mouseX = e.clientX;
          mouseY = e.clientY;
          //console.log("mousemove");
        })
        
        
        intervalCursor = setInterval(move,1000/60);
        function move(){
          projectPreview.x = lerp (projectPreview.x, mouseX, 0.1);
          projectPreview.y = lerp (projectPreview.y, mouseY, 0.1);
          projectPreview.update() 
          console.log("move");
        }
        
        function lerp (start, end, amt){
          return (1-amt)*start+amt*end
        }

    } else if (!$('.projects').hasClass('run-preview')) {
        clearInterval(intervalCursor);
        //$('#content-container').addClass('test');
    }
 
  }
})

.observe(runPreview, { attributes: true });

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

Generate a customized form based on selected radio button option

Hey there! I'm curious to know if it's achievable to utilize Javascript/jQuery or Ajax in displaying a form depending on a radio button selection. Here's the scenario: I have two unique forms. If one radio button is chosen, I'd like to ...

How can I prevent query string parameters from being sorted in React Router?

I'm having trouble setting a Route path with a query string using react-router. The issue is that react-router always arranges query params alphabetically, resulting in a sorted query string in the URL. For instance, on a location filter page where I ...

Updating a list of books from a form in another component: Step-by-step guide

Hello everyone, I am fairly new to using React and am currently following a tutorial on creating a book library. In this project, I have an AddNewBook Component which is essentially a form structured as follows: function AddNewBook(){ const [name, setNam ...

Spin the connections around a circular path

I'm interested in creating a website where links rotate around a circle, similar to this example: https://i.sstatic.net/103mx.jpg. The links will display different images and texts leading to various URLs. I want the images to form a unified rotation ...

Displaying a JavaScript array containing multiple arrays

I have a collection of arrays, each containing a set of list items, which I am displaying using console.log(jobsList);. The output looks like this: The variable jobsList is generated by adding arrays created inside a for loop like this: for (var i=0; i ...

What is the best way to identify the clicked cell?

I'm a JavaScript newbie trying to work with ExtJS 3.4. I've set up a basic tree with 3 columns and now I want to figure out which cell, row, or column has been selected. Currently, I'm following the example provided by Sencha at : var tr ...

Encountering an issue in my Next.js application with the app router where I am unable to read properties of undefined, specifically in relation to '

As I develop a basic Rest API in Next.js, my goal is to display "Hello world" in the console for a post api. export const POST = (req: Request) => { console.log('hello world'); }; The error message that appears in my terminal is as follows: ...

Exploring Three.js on Cordova with WebGL

I am working on developing a mobile app using Three.js on Cordova. While the app runs smoothly on a PC browser, it encounters an issue when trying to create the WebGL context on a Samsung Note 3 device. The specific error message is: THREE.WebGLRenderer ...

Using Vue JS to create advanced select dropdowns

In the process of developing an application that relies on dropdown menus to assign input fields from a CSV file, I encountered a challenge. I wanted to incorporate logic that would automatically select certain options based on specific conditions. However ...

perform asynchronous calls within a for loop in a synchronous manner

Having issues with managing asynchronous events in sails.js. Obtaining data from a JSONapi and attempting to insert it into the database sequentially within a for loop. The goal is to maintain the correct order of execution. For simplicity, consider the f ...

When selecting an option from jQuery autocomplete, the suggestions data may not always be returned

I have a question about the jQuery autocomplete feature. In my code snippet below, I have an input with the ID aktForm_tiekejas that uses the autocomplete function: $('#aktForm_tiekejas').autocomplete({ serviceUrl: '_tiekejas.php', wid ...

How can I retrieve the position of a specific string within a redis list?

In my game, I have a list of current players and keep track of the turn with an integer. When a player leaves, they are removed from the list, and in some cases, I need to adjust the turn value as well. I've observed that if a player's index is ...

Securing a route using a referrer in Node.js: Best practices

Within my node.js application, I am looking to secure a specific route so that users can only access the page /post if they are coming from /blog. If the user accesses the route from any other source, they should be redirected to /. I have implemented the ...

Is it advisable to start a function within the componentDidMount() method in ReactJS when using promises?

I am developing an application that utilizes promises to manage animations. After a few attempts, I encountered the following error message: Warning: Can’t call setState on a component that is not yet mounted. This is a no-op, but it might indica ...

Connecting a Date object by using :value and @input within a VueJS component

Successfully linking a date form input with a date object using :value and @input instead of v-model as outlined in this method has been a great ongoing experience. It allows for displaying and modifying the date in the form input, as well as saving the up ...

What are some effective ways to utilize localstorage efficiently?

I've been working on creating a variable that stores its value across multiple pages using local storage. However, I've encountered an issue where the variable is not being saved, and there are no error messages to help diagnose the problem. Her ...

Troubleshooting JavaScript directly on the client side

As a JavaScript beginner hoping to transform into a JavaScript expert, debugging is an essential skill I must master. Currently, I am utilizing Chrome debugger tools to tackle a complex array of spaghetti JavaScript code that resembles a cryptic puzzle wai ...

Merging and sorting a two-dimensional array in JavaScript

Given the following 2D array: 1230 | this is a test 1278 | my new test 1230 | test2 7654 | testing... I am looking to transform the array so that values in the first column are unique and the second column stores the concatenated text associated with eac ...

Using Vue.js to connect v-html to a custom CSS stylesheet

I am currently working with HTML generated by a function on an external server and I am able to preview this within a tag. Additionally, I can retrieve the CSS information in a similar manner. <template> <div v-html="html"></div ...

Sending an array of complex data to a controller method in ASP.net MVC

Currently, I am in the process of migrating an ASP.net Web Forms application to MVC. This application makes use of AJAX through an Ajax-enabled WCF Web service and asp:ScriptManager. I have been sending an array of objects to the service, and it has been ...