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);


        }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật