Halt the execution of code once the user unselects the div

Is there a way to prevent the setInterval function from running when the user unselects the div they originally selected? I've tried using clearInterval but it's not working. Also, utilizing the cvalue from this doesn't seem to update within the code. Any suggestions?

 $(document).on("click",".profTemp", function()
                { 
                  var pollingUser;
                  if(!$(this).hasClass('selected'))
                  {
                    var chosenUser;
                    var previous = null;
                    var current = null;
                    var assigned = false;

                    chosenUser = $(this).children('span').text();
                    chosenUser = chosenUser.trim();

                    console.log(chosenUser);
                    $(this).toggleClass('selected');

                    pollingUser = setInterval(function()
                    {

                      console.log(chosenUser);
                      $.ajax({
                        url: '/getJSON',
                        dataType: 'json',
                        success: function(response) {
                          console.log(response + "84897348");
                          obj = JSON.parse(response);
                          console.log(chosenUser + "inside success");

                          var changeTo;
                          var deviceID;

                          console.log(current + "current");
                            for(var i = 0; i < obj.clients.length; i++)
                            {
                              if((chosenUser == obj.clients[i].userName) && (assigned == false))
                              {
                                console.log(chosenUser + " inside if");
                                current = JSON.stringify(obj.clients[i]);
                                changeTo = obj.clients[i].uri;
                                device = obj.clients[i].deviceID
                                assigned = true;
                              }
                            }
                            assigned = false;

                            console.log(current + " current");
                            console.log(previous + "previous");

                            if(previous !== current)
                            {          

                              console.log("ARE WE INSIDE HERE");

                              $.ajax({
                                url: 'https://api.spotify.com/v1/me/player/play',
                                contentType: 'application/json',
                                type: 'PUT',
                                dataType: 'json',
                                headers: {
                                  'Authorization': 'Bearer ' + access_token
                                },
                                data: JSON.stringify({"uris":[changeTo], "device_id":device, "offset": { "uri":changeTo} }),
                                success: function(response) {
                                  console.log(response);
                                }
                              });
                            }
                          }
                        });
                      previous = current;
                      console.log(chosenUser);
                    }, 2000);
                  }

                  else if($(this).hasClass('selected'))
                  {
                    $(this).toggleClass('selected');
                    console.log("not selected");
                    clearInterval(pollingUser);
                  }       

                }); 

`

Answer №1

var pollUser is where you should expect the id of the setInterval to be located, right? Because in the function later on, you assign

pollUser = setInterval(function()...
. Check out the documentation on setInterval.

The issue here is that every time there is a click event on .profTemp, a new variable pollUser is being created with var pollUser at the beginning of your function.

If you want the ID of your setInterval to persist, you need to store it in a variable outside the scope of the .profTemp click handler function, so it remains intact.

For more information on function scope, check out additional resources.

Also, learn about using "var" in JavaScript.

Answer №2

Make sure to declare the variable pollUser before defining the onclick function.

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

List of elements inside an HTML box

In my current HTML project, I am trying to include a box on a webpage that contains a scrollable list of elements. I want the content inside the box to scroll independently without affecting the rest of the page. Is there a way to achieve this? ...

Add information to the <script> tag

There is a row that I sometimes clone. <script id="SubRow10" type="text/template"> <select id="SubSelect10" class="form-control" name="SubcategorySelect" required> <option value="m,2">Op1</option> <option value="m,3"&g ...

What is the best way to send an Object to the page component while implementing Dynamic Routing in NextJS?

I am currently utilizing the "app" router within NextJS and aiming to implement Dynamic Routes in order to dynamically generate pages for blog posts. The issue I'm facing involves passing an Object to the dynamically created page, specifically a Post ...

Accessing the current state outside of a component using React Context

As I delve into creating a React application, I find myself in uncharted territory with hooks and the new context API. Typically, I rely on Redux for my projects, but this time I wanted to explore the context API and hooks. However, I'm encountering s ...

The evolving impact of the HTML5 <video> element

I've been attempting to find information on this topic, but unfortunately my search has not been very successful. I vaguely recall coming across a tutorial that covered something like this. Does anyone happen to know how to alter the perspective of a ...

Guide on extracting URLs from an XML sitemap URL by utilizing PHP

<?php function retrieveURLsFromSitemap($sitemapUrl) { $xml = simplexml_load_file($sitemapUrl); if ($xml === false) { die('Error loading XML'); } $urls = []; foreach ($xml->url as $url) { $urls[] = (str ...

Ways to automatically close the external window upon logging out in Angular 12

I have successfully created an external window in my Angular application. Everything is working as expected, but I am facing an issue when trying to automatically close the external window upon user logout. Although I have written the code below and it wo ...

Leveraging the power of Jquery's .each method inside a PHP foreach iteration

I am new to utilizing jquery, and I encountered an issue with using the .each function within a php foreach loop. I am attempting to create a table that calculates quantity, unit price, and total price. Since I don't know how many table rows the user ...

Animation glitch when clicking on hamburger menu symbol

I am facing an issue where, in mobile window mode, if I click on the burger icon and then zoom out to a larger resolution and zoom back in to mobile size, clicking on the burger icon does not activate the slide-down menu as expected. You can see the issue ...

Testing a cucumber scenario by comparing the redirect URL with a different URL

Currently, I am working on writing Cucumber tests for my project. One issue I have encountered is that when clicking a certain button in my code, it redirects to another page with a fixed URL. How can I retrieve the current URL within the Cucumber test? I ...

Leveraging the power of the mongoDB database in conjunction with node.js through

Trying to set up mongoDB with the driver has been quite a task. For starters, I followed this guide to install mongoDB on my Windows machine: https://medium.com/@LondonAppBrewery/how-to-download-install-mongodb-on-windows-4ee4b3493514. Next, in acc ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...

Toggle class on child element when parent is clicked

I am currently working on a functional React component that looks like this: const RefreshButton = () => ( <IconButton> <RefreshIcon /> </IconButton> ) My goal is to dynamically assign a class attribute ...

Update breadcrumbs dynamically by clicking on each horizontal panel

I've been dealing with a problem for the past 24 hours. I want to implement a horizontal accordion with breadcrumbs on a webpage. How can I achieve this dynamically, so that when a user clicks on any link in the accordion, the breadcrumbs update simul ...

Developing a personalized data binding feature with AngularJS and utilizing ng-repeat

Looking to design a unique controller that can display multiple similar objects connected to a dataset structured like this: [{name: card1, values: {opt1: 9, opt2: 10}},{name: card1, values: {opt1: 9, opt2: 10}}] The goal is to showcase the name and one ...

After deployment, certain formatting elements appear to be skewed in the React application

After developing a React app with create-react-app, everything was working perfectly. However, upon deployment, I noticed that some styles weren't showing up as expected. The majority of the styling from Material UI is intact, but there are a few dis ...

One Page HTML5 with a Bootstrap fixed top menu, revealing content on menu item click

Is there a way to have the Bootsrap mobile menu automatically unfold when a link (anchor on the same page) is clicked? The menu unfolds with class navbar-collapse collapse in The menu folds with class navbar-collapse collapse out I already have an oncl ...

Determining the optimal time to utilize the addClass function in jQuery and CSS

One of my HTML elements has the class "article": <article> Content </article> In my jQuery script, I want to add specific classes that have been predefined: $('article').addClass('rounded box-shadow gradient-bright'); I ...

Conceal elements when they are too small without the use of JavaScript

I want to be able to hide content when the window size is below a certain point. After finding an example at (http://css-tricks.com/dynamic-page-replacing-content/), I still couldn't figure out why it actually works. <div class="container"> ...