I am facing an issue with the clearTimeout function in my JavaScript code. Can anyone help

I am encountering some issues with the clearTimeout() function.

The setTimeout() function is working as expected, but I want it to stop running when I close my notification.

I'm not sure what is causing the problem in my function.

After closing the notification, I am seeing this error message in my console:

Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Thank you!


class Notification {
  addNotification() {

    let notificationContent = `Content <div onclick="notify.closeWindow(event)"></div>`;

    let notifyArea = document.createElement("div");
    notifyArea.classList.add("notification-area");

    let notification = document.createElement("div");
    notification.classList.add("notification");
    notification.innerHTML = notificationContent;

    const area = document.querySelector(".notification-area");

    let firstTimer;
    let secondTimer;

    if (!area) {
      document.body.appendChild(notifyArea);
      notifyArea.appendChild(notification);

      if (notification == null) {
        clearTimeout(firstTimer);
      } else if (notification) {
        firstTimer = setTimeout(() => {
          notifyArea.removeChild(notification);
        }, 10000);
      }
    } else {
      area.appendChild(notification);

      if (!notification) {
        clearTimeout(secondTimer);
      } else {
        secondTimer = setTimeout(function() {
          area.removeChild(notification);
        }, 10000);
      }
    }

  closeWindow(e) {
    e.target.parentElement.parentElement.remove();
  }
  }

Answer №1

When clearing timers in the closeWindow function, ensure that they are properly set as properties of the class. Otherwise, the removeChild function may be called after the node has already been removed.

class CustomNotification {
  showNotification() {

    let notificationContent = `Some Content <div onclick="customNotification.closeWindow(event)"></div>`;

    let notificationArea = document.createElement("div");
    notificationArea.classList.add("notification-area");

    let notificationElement = document.createElement("div");
    notificationElement.classList.add("notification");
    notificationElement.innerHTML = notificationContent;

    const existingArea = document.querySelector(".notification-area");

    this.firstTimer;
    this.secondTimer;

    if (!existingArea) {
      document.body.appendChild(notificationArea);
      notificationArea.appendChild(notificationElement);

      if (notificationElement == null) {
        clearTimeout(this.firstTimer);
      } else if (notificationElement) {
        this.firstTimer = setTimeout(() => {
          notificationArea.removeChild(notificationElement);
        }, 10000);
      }
    } else {
      existingArea.appendChild(notificationElement);

      if (!notificationElement) {
        clearTimeout(this.secondTimer);
      } else {
        this.secondTimer = setTimeout(function() {
          existingArea.removeChild(notificationElement);
        }, 10000);
      }
    }

  closeWindow(e) {
    clearTimeout(this.firsTimer);
    clearTimeout(this.secondTimer);
    e.target.parentElement.parentElement.remove();
  }
}

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

JS form validation malfunctioning

XHTML <form name="suggestion" method="post" action="suggestion.php" class="elegant-aero" onSubmit="return validate()" > <label> <span>Message :</span> <textarea id="Message" name="m ...

The CSS hamburger menu halves in size when being closed

I have successfully created a CSS/JS hamburger menu with a transforming icon upon clicking. However, I encountered a bug where, upon clicking the 'close' button on the hamburger, the navigation menu cuts behind the header, resulting in a messy ap ...

Having trouble finding the right path. Is there an issue with Angular routing?

After successfully creating a simple application, I decided to write test cases for it. My first attempt was to work on the routing part of the application. Check out the code on StackBlitz The routing code snippet is as follows: Main module: export cons ...

Associate an alternate attribute that is not displayed in the HTML component

Imagine there is a collection of objects like - var options = [{ id: "1", name: "option1" }, { id: "2", name: "option2" } ]; The following code snippet is used to search through the list of options and assign the selected option to anot ...

Guide on receiving application/csp-report as json in an express application utilizing bodyParser

I am currently working on creating a middleware that can receive CSP reports from browsers. Browsers send these reports with the Content-Type of application/csp-report, and the data is in JSON format. Right now, I'm using bodyParser.text to handle thi ...

Encountering the issue: receiving an error message stating that shuffle(...) is undefined within

Whenever I try to add it into the app.js file, it keeps coming up as undefined. app.js (function () { var tkcApp = angular.module('TKC', []); var shuffle = function (o) { for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

Transferring mouse events from iframes to the parent document

Currently, I have a situation where my iframe is positioned over the entire HTML document. However, I am in need of finding a way to pass clicks and hover events from the iframe back to the main hosting document. Are there any potential solutions or alter ...

Cypress test never finishes when an unforeseen alert is triggered in the system during the test

When a web application unexpectedly throws an error using an alert box, the Cypress test becomes stuck indefinitely. The test will not complete or fail until the user manually closes the browser or clicks on the OK button within the alert box. I have crea ...

Nextjs: Issues with Dropdown functionality when using group and group-focus with TailwindCSS

My goal is to make an array visible once a button is clicked. By default, the array should be invisible, similar to drop-down menus in menu bars. I am utilizing the group and group-focus classes. While the array disappears as expected, it does not reappear ...

What is the best way to retrieve a URL from a function in an HTML/JavaScript environment?

Recently, I delved into learning HTML and JavaScript. One of the challenges I encountered is figuring out how to access a URL or download a file from a function written in JavaScript that was imported from another file using: <script src="jscriptSheet. ...

Instructions for transferring a JavaScript array to a Java servlet

Greetings everyone! I am currently working on a web application with an orthodox approach, utilizing AJAX in Java and JavaScript. I am wondering if it is feasible to pass an array from JavaScript to a Servlet. ...

methods for converting an array to JSON using javascript

Our team is currently working on developing a PhoneGap application. We are in the process of extracting data from a CSV file and storing it into a SQLite database using the File API in PhoneGap. function readDataUrl(file) { var reader = new FileReade ...

The function being called within useEffect is rendering too quickly, causing it to break. However, it functions correctly after

When using React-id-swiper to load images for products, I encountered an issue with setting the useState 'loading' state to false after all images have been successfully loaded. In this case, there are 5 products. To achieve this, I implemented ...

Troubleshooting video streaming loading issues caused by 404 errors in URL paths with videojs

I've been successfully using the video.js library to stream live video. Everything was going well until after a while, the URL started throwing a 404 error during streaming, causing the entire player to get stuck on loading. Now I'm looking for a ...

Styling elements using the nth-child selector in JavaScript

I am trying to apply a CSS class based on the combined height of the 2nd and 3rd child elements. For example, if the height of the 2nd child plus the height of the 3rd child equals a certain value, I want to add a specific class. Here is my JavaScript cod ...

Issue with Angular 2 pipe causing unexpected undefined result

Here is a JSON format that I am working with: [{ "id": 9156, "slug": "chicken-seekh-wrap", "type": "dish", "title": "Chicken Seekh Wrap", "cuisine_type": [2140] }, { "id": 9150, "slug": "green-salad", "type": "dish", "title": "Green Sala ...

Dynamically inserting templates into directives

I've been attempting to dynamically add a template within my Angular directive. Following the guidance in this answer, I utilized the link function to compile the variable into an HTML element. However, despite my efforts, I haven't been success ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...

Passing a variable in an AngularJS $http.get() call to retrieve a specific section of a JSON data file

Currently, I am using json files to stub my $http.get() calls. I am trying to retrieve a specific subset of the json file in my angular controller. Despite looking at other solutions that recommend setting a params property in the Get call, it does not see ...