Stop notification from duplicating

I am working on a bell notification. Notifications should appear in notification pop up when clicked bell icon and when user scrolls to the bottom it should send get request to the backend and fetch older notifications.

  1. If theres global notification, it will stick as 1st notification and rest of the personal notification appear below it.
    2)The Personal notification (notification that is not global), older ones should appear in the bottom and newer ones should appear in the top (without having to refresh the page).

The problem: newer notifications appear in the top but the same notification appear in the bottom as well. Example:

current notification box :H,G,F

new notifications has been added to the database -> updated notification box: I,H,G,F,I

scrolls to the bottom and older notifications get loaded ->updated notification box :I,H,G,F,I,E,D,C

refeshes the page ->current notification box: I,H,G

scrolls to the bottom and older notifications get loaded -> current notification box: I,H,G,F,E,D

As shown in example it works fine when refreshed the page but it shows duplicated when its not. Also any advice for the code is welcomed.

 $(document).ready(function() {

        var pageNumber =1;
        var displayNotificationOnId = [];
        var newNotificationIds = [];
        var loading = false;
        var loadDelay = 4000;

        var bellClickedToOpen = true;


        function getNewNotifications() {

            $.ajax({
                type:'GET',
                url:'/notifications?page=' + pageNumber,
                success: function (data) {
                    populateNotifications(data.notifications);
                    data.notifications.forEach(function(dta){
                        if (!newNotificationIds.includes(dta.id)) {
                            newNotificationIds.push(dta.id)

                        }
                    })
                    console.log(data)
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching new notifications:', error);
                }
            })
        }

        // $(document).ready(function() {
        $('#notificationDropdown').on('scroll', function() {
            var container = $(this);
            var scrollPosition = container.scrollTop();
            var containerHeight = container.innerHeight();
            var contentHeight = container[0].scrollHeight;

            var distanceBottom = contentHeight - (scrollPosition + containerHeight);

            var threshold = 50;
            // Check if the scroll position is near the bottom of the container
            if (distanceBottom <=threshold && !loading ) {

                loading = true


                $('#loading').show();
                console.log("inside if statement" + loading)

                setTimeout(function () {
                    console.log("reached bottom of the popup")
                    pageNumber +=1;
                    getNewNotifications(pageNumber); // Fetch new notifications when near the bottom
                    loading = false;
                    $('#loading').hide;

                }, loadDelay)

            }
        });
        // });


        function fetchNotificationCount () {
            $.ajax({
                url : '/notifications',
                method: 'GET',
                success: function (data) {
                    var notifications = data.notifications;
                    if(data.newNotificationsCount>0){
                        $('#notificationBadge').text(data.newNotificationsCount).show();
                        $("#readAll").removeClass("disabled-link");
                        console.log(">0" + data.newNotificationsCount);
                    } else {
                        $('#notificationBadge').hide();
                        $("#readAll").addClass("disabled-link");
                        console.log("else" + data.newNotificationsCount);
                    }
                    // $('#notificationBell').click(function() {
                    populateNotifications(notifications);

                }, error: function (xhr, status, error) {
                    console.error(error);
                }
            })
        }

        fetchNotificationCount();
        setInterval(fetchNotificationCount, 5000);


        function markSingleNotificationAsRead(id, read){

            console.log(id, read);


            var isUnread = read ===0;


            var buttonText = isUnread ? "Unread":"Read";

            var $button = $('.mark-as-read-btn[data-notification-id="' + id + '"]');

            $.ajax({
                url:`/notificationsRead/${id}`,
                method: 'POST',
                success: function(response) {
                    console.log("Notification marked as " + buttonText + " successfully");
                    $button.text(buttonText);

                },
                error:function (xhr, status, error) {
                    console.error('Error marking notification as read:', error);
                }
            })
        }

        function populateNotifications(notifications) {
            // var $notificationList = $('#notificationList');
            // $notificationList.empty(); // Clear existing notifications
            var globalNotificationDiv = $('#global-notification');
            var hasGlobalNotification = false;

            console.log(notifications);

            var globalNotifications = notifications.find(function (notification){
                return notification.type === 'global';
            })

            if (!globalNotifications) {
                // alert("hello")
                globalNotificationDiv.empty();
            }
            if(globalNotifications && !displayNotificationOnId.includes(globalNotifications.id)) {
                console.log(globalNotifications)
                // console.log(globalNotifications.expired)

                displayNotification(globalNotifications, true)
            }

            // notifications.forEach(function(notification) {

            for (var i=0; i<notifications.length; i++) {
                var notification = notifications[i];
                var buttonText = notification.read === 0 ? "Unread" : "Read";
                var notificationClass = notification.read === 0 ? "unread-notification" : "";

                if (!displayNotificationOnId.includes(notification.id)) {
                    displayNotification(notification, false);
                    console.log(displayNotificationOnId, notification.id);
                }
            }



            // });

            $('#notificationBell').click(function (){
                $('#notificationDropdown').show();

            })


        }



        function displayNotification (notification, isGlobal) {
            var $notificationList = $('#notificationList');
            var globalNotificationDiv = $('#global-notification');
            var greaterThanLargestId= false;

            var notificationRead = notification.read ===0 ? "unread-notification" : "";
            var disableClick = isGlobal ? "disable-globalNotification" : "";

            var daNotifications = `
                    <div class="list-group-item ${notificationRead} ${disableClick}"  >


                        <a  href= "${notification.url}" class="mainNotiHeader" data-notification-global="${notification.type}"   data-notification-id="${notification.id}" data-notification-read="${notification.read}" >
                            <div class = "notificationInfo">
                                <h4  class="list-group-item-heading">${notification.tool}</h4>
                                <p >${notification.created_at}</p>
                            </div>
                            <p class="list-group-item-text" >${notification.text}</p>
                        </a>



                    </div>

`;

            if (!displayNotificationOnId.includes(notification.id)) {

                for (var i = 0; i<displayNotificationOnId.length; i++){

                    if (notification.id >displayNotificationOnId[i]){
                        greaterThanLargestId = true;
                        break;
                    }

                }
                if (greaterThanLargestId) {


                    $notificationList.prepend(daNotifications);
                    greaterThanLargestId= false;
                    displayNotificationOnId.push(notification.id);


                }
            }

            if(isGlobal) {
                globalNotificationDiv.html(daNotifications);

            } else if (greaterThanLargestId === false) {
                console.log("!greaterThanLargestId: " +greaterThanLargestId  )
                $notificationList.append(daNotifications);
                displayNotificationOnId.push(notification.id);
                
            }
            if (isGlobal) {
                globalNotificationDiv.find('.disable-globalNotification').click(function (event){
                    event.preventDefault();
                })
            }

            console.log("line 494" + displayNotificationOnId);


        }