execute a function within a setInterval loop

I need to execute a function when the timer reaches 0. Upon clicking a card, a popup appears and the countdown begins. Here is my current code:

openModal() {
  switch (area) {
    case 'a':
      var self_t = this;
      uid = 11;
      let timer = 20;
      let interval = setInterval(function () {
          let elementID = document.getElementById('float-div');
          if(elementID == null) {
            timer = this.inSeconds;
          }
          if(timer >= 0) {
            if(elementID) {
              elementID.innerHTML = String(timer);
            }
          }
          if (--timer == 0) {
              if(elementID) {
                  elementID.innerHTML = '0';
              }
              if(area == "a") {
                 self_t.callFunction(uid); // debugger shows it not reaching here                          
                 clearInterval(interval);
              }
          }
    }, 1000);
    break;

    case 'b':
    console.log('something else');
    break;
  }
}

callFunction(uid) {
  console.log(uid);
}

already attempted: using var self=this

If I use this.callFunction(uid), then it results in an error.

Answer №1

To optimize your code, consider utilizing arrow functions. Below is a code snippet that demonstrates how to implement arrow functions effectively. Check out this resource for more information on arrow functions.

openModal() {
  switch (area) {
    case 'a':
      uid = 11;
      let timer = 20;
      let interval = setInterval(() => {
        let elementID = document.getElementById('float-div');
        if (elementID == null) {
          timer = this.inSeconds;
        }
        if (timer >= 0) {
          if (elementID) {
            elementID.innerHTML = String(timer);
          }
        }
        if (--timer == 0) {
          if (elementID) {
            elementID.innerHTML = '0';
          }
          if (area == "abc") {
            this.callFunction(uid); // debugging issue here                          
            clearInterval(interval);
          }
        }
      }, 1000);
      break;

    case 'b':
      console.log('something else');
      break;
  }
}

callFunction(uid) {
  console.log(uid);
}

UPDATE:

The statement var self_t = this; is unnecessary when using arrow functions since the context (this) is preserved within the function itself.

I hope this clarification helps :)

Answer №2

Consider making some adjustments to this code snippet

 if(elementID == null) {
            timer = this.inSeconds;
          }

by changing it to

 if(elementID == null) {
            timer = self_t.inSeconds;
          }

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

Monitoring the download status in the web browser: Angular 5

Currently, I'm in the process of developing an application that interacts with a REST API to download files. As per the API's behavior, it responds with the file immediately upon request. So, I've implemented the following logic to facilitat ...

Angular 2 Quickstart encountered a 404 error when trying to retrieve the /app/main.js

I'm attempting to follow the Angular 2 quickstart guide, but I'm having trouble getting it to work. I've searched for similar questions but haven't found a solution yet. Can anyone assist me with this? Here is my code: app.component.t ...

Modify the JavaScript window.navigator

I am attempting to modify window.navigator, but am facing difficulties in doing so: -- [10:40:28.802] window.navigator['buildID']; [10:40:28.811] "20121129162756" -- [10:40:47.225] window.navigator['appCodeName'] = "I want to change it ...

Is there a way to interact with specific locations on an image by clicking in JavaScript?

https://i.stack.imgur.com/gTiMi.png This image shows a keypad with coordinates for each number. I am able to identify the coordinates, but I am struggling to click on a specific coordinate within the image using JavaScript. Can someone assist me in achiev ...

Refreshing an iframe located on disparate domains

There is a webpage called "main.jsp" within the domain "domain1". This page contains an iframe that loads content from another domain known as "domain2". Essentially, "main.jsp" serves as a common content platform, with the iframe displaying content from v ...

What is the process by which Single Page Applications manage the Not Modified 304 response?

Imagine a scenario where a Single Page Application (SPA) built using angular or vuejs loads 3 components on a page, with each component making requests to different backend APIs. Now, if a user decides to refresh the page, those same 3 API calls are trigg ...

Cleanse the array in jQuery by removing any unusual characters

I have a specific task involving an array that needs to be sent to a web service. The URL in question is as follows: http://localhost:4025/vmp_webservice.asmx/LoadService2Daily?fromDate=2014-05-26+00%3A00%3A00&toDate=2014-05-26+23%3A59%3A01&campa ...

Instructions for positioning two 3D models within separate div elements using Three.js

The website contains various divs with classes such as "skin", "skin2", "skin3"... And each class corresponds to a different 3d model that needs to be placed. I am attempting to achieve this, but all the 3d models seem to be c ...

Incorporating Custom Scrollbars in TinyMCE Editor: A Step-by-Step

I'm looking to incorporate a custom scroll bar into the TinyMCE Editor. Can you provide guidance on how to do this? Visit this URL for more information: ...

Implementing Cross-Origin Resource Sharing (CORS) in play-framework version 2.5.x: A Step-by-Step Guide

My current challenge involves retrieving JSON data by sending a request to a Restful URL from localhost within an AngularJS-1 application. The error that I encounter is as follows: http://localhost:9000/mlm/user/all Failed to load resource: the server r ...

Implementing caching for ajax JSON requests can improve performance and optimize data

Looking to optimize my basic Ajax call for parsing a JSON file. I want to avoid hitting the feed every time someone visits the page. Any suggestions on how to implement caching so that the feed is only requested, let's say, once every 2 hours? $(fun ...

Need to return to the previous page following submission

Is there a way to redirect me to the premontessori page after I submit the form? Below is my function handleSubmit: handleSubmit(event) { event.preventDefault(); <Link to='/premontessori' style={{textDecoration:'none'}} & ...

Troubleshooting problem with BxSlider and collapsible elements in Bootstrap

I'm facing a challenge trying to integrate a bootstrap collapsible element into a bxslider slide without success. Does anyone have any suggestions on how to resolve this issue? Feel free to check out my sample code on the following link: ...

When using Express.static, the website functions properly but an error message "GET http://localhost:5000/index.js net::ERR_ABORTED 404 (Not Found)" is displayed

Having an issue with express.static. My project is a basic portfolio website that includes a form for sending emails. I referred to this tutorial on Nodemailer: Tutorial Nodemailer Github The problem arises within my index.html file (this example applies ...

Error in Subscribing to Angular 8 Async Pipe

Check out this Full StackBlitz example: https://stackblitz.com/edit/angular8-async-pipe The app component template contains three identical components: <app-loader></app-loader> <app-progress></app-progress> <app-spinner>< ...

How to properly pass data between parent and child components in VueJS without using provide/inject

I've been experimenting with using provide and inject to pass data from parent to child elements, but I'm running into an issue where the data isn't available in the child element. It's strange because when I add the same data directly ...

What steps should I take to update my Vue 2 components for use in Vue 3?

I am considering using my Vue 2 components in a new Vue 3 project, is this possible? For example, I currently have Vue 2 components for "FAQ" and "About Us". Can I incorporate these components into a Vue 3 project by creating routes to use them? I initiall ...

Function within a while loop

I am attempting to retrieve the content of a specific textarea tag when a particular button is clicked. I believe that using a loop would be helpful in this situation. In PHP, the while loop can be used to dynamically change the name of the textarea and ...

Bootstrap 4: The mystery behind why the popover fails to appear inside a scrollable dropdown

Is there a way to replicate the behavior of Bootstrap 3 dropdowns with scrollbars on hover and popovers in Bootstrap 4? It seems that setting overflow:hidden; for scrolling functionality in dropdown menus also hides the popover. I have tried using containe ...

Fetch request encountered a 500 error due to the absence of the 'Access-Control-Allow-Origin' header on the requested resource

Currently, I am in the process of developing a front-end web application using create-react-app and need to make a request to the ProPublica API. The fetch call code snippet is as follows: export const fetchSenators = () => dispatch => { fetch(' ...