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

Avoid consistently updating information

I am experiencing a strange issue in my project. I have 2 tabs, and in one tab, there are checkboxes and a submit button. The user selects items from the checkboxes, and upon clicking the button, they should see their selections in the other tab. This fu ...

Encountering an issue with WebRTC where the 'addIceCandidate' function on RTCPeerConnection is failing, resulting in an error displayed on the console. However, despite this error

I am facing an issue with connecting two peers using webRTC. While I can successfully display both local and remote videos, as soon as the remote video appears, the candidate object turns null and an error message is logged on the console. TypeError: Fail ...

Tips for setting a value in $scope within an ng-repeat loop in AngularJS

I'm currently facing an issue with ng-repeat in angularJS, specifically on how to assign a value in $scope inside ng-repeat. Here is my scenario: I have a JSON file that contains all the data structured like this: [ {BookID:1,Chapter:1,ContentID:1, ...

The issue with Angular JS is that it fails to refresh the select and input fields after selecting a date

Currently utilizing Angular JS and Bootstrap, I have a query regarding updating the input for a datepicker calendar and a select from a function. The values are being successfully updated, however, they do not reflect on their respective inputs. It seems ...

Utilize the double parsing of JSON information (or opt for an alternative technique for dividing the data

Looking for the most effective approach to breaking down a large data object retrieved from AJAX. When sending just one part (like paths), I typically use JSON.parse(data). However, my goal is to split the object into individual blocks first and then parse ...

Exploring the best way to use $set in Mongoose for dynamically updating an embedded

I'm currently attempting to create a unique function that can update the value of a specific embedded MongoDB document within an array. The goal is to change the value based on its position. function removeAddress(accountNum, pos) { const remove ...

Updating a child component in React while applying a filter to the parent component

Although I've come across this question before, I'm struggling to comprehend it within my specific scenario. I'm currently using a search bar to filter the data, which is functioning properly. However, the image is not updating. The URL bei ...

Testing the speed of the client's side

In my quest to create an application that allows users to conduct a speedtest on their WiFi network, I have encountered some challenges. While standalone speedtest apps like Speedtest.net and Google exist, server-based speed test modules from NPM are not s ...

Is it necessary to include a request in the API route handler in Next.js when passing parameters?

In my API route handler, I have a function for handling GET requests: import { NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest, { params }: { params: { id: string } }) { const { id } = params; try { ...

Tips for detecting when a browser is closing in a web application that is integrated with a master page

Currently, I am working on a web application that uses a master page. I need to be able to detect when the user is closing the browser so that I can raise an event to clean up session variables. I attempted using the unload JavaScript event, but it seems ...

What could be causing the issue when the selected option is being changed and the condition does not work

Whenever the selection in a select element is changed, the corresponding text should also change. Check out this Fiddle here. (function($) { 'use strict'; function updateResultText() { var s1_is_1 = $("#s1").value === '1', ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Exploring the synergies of Remark and Rehype plugins alongside MDX in Next.js powered by @next/mdx

I’ve been experimenting with Github Flavored Markdown using @next/mdx, but I’m struggling to understand how to use plugins alongside the code. Here’s a breakdown of what I’ve attempted so far: (I’m following the instructions from the Next.js Doc ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

The handleClose() function in React is currently writing to the console but failing to close the child element

Currently, I am in the process of creating a small online store for my personal business. Although I have limited experience with React, I believe I have managed to make some progress and might be able to complete something that is at least functional, eve ...

Having trouble making md-data-table directives function properly

I'm struggling to incorporate the md-data-table library from https://github.com/daniel-nagy/md-data-table into my webpage. Despite loading the library in Chrome, none of the directives seem to be working. Here's a snippet of my code - can anyone ...

Looking for the quickest hash and salt method for IP addresses in Node.JS?

Currently, there are many stipulations regarding the tracking of user data such as unique visits and returning users. An issue arises in certain regions where IP addresses are considered sensitive personal information. To continue identifying unique user ...

Encountering an issue with postman where properties of undefined cannot be read

I am facing an issue while trying to create a user in my database through the signup process. When I manually enter the data in the create method, it works fine as shown below: Note: The schema components are {userName:String , number:String , email:Stri ...

Concealing empty rows within a vertical v-data-table using Vue

Below is the code that can be run to showcase my issue. Design: <div id="app"> <v-app id="inspire"> <v-data-table :headers="headers" :items="desserts" hide-default-header ...