채택완료

상품리스트 불러오는 스크롤 하단에 닿으면 리스트호출을 하는되요 중복이 됩니다.

안녕하세요

상품리스트 불러오는데,

스크롤 하단에 닿으면 리스트호출을 하는되요.

중복이 됩니다.

소스튼 다음과 같습니다.

---

var didScroll;

// 스크롤 체크

$(window).on('scroll', function () {

didScroll = true;

});

// 스크롤이 하단에 닫으면 인피니트컨텐츠 호출

setInterval(function () {

var bottomHeight = $(window).scrollTop() + $(window).height() + 600;

var docHeight = $(document).height();

if (didScroll) {

if (bottomHeight > docHeight) infiniteScrollContent();

didScroll = false;

}

}, 250);

// 데이터 호출하는데 기홀출된 목록이 숫자 비교해서 다음 목록가져옴

function infiniteScrollContent() {

var total = $("#ajax_data > li.shopThumb").length;

if (total >= _total_count) {

didScroll = false;

} else {

console.log('스크롤 으로 리스트가져오기', total);

get_shop_list(_count,total,_shopRegion,_shopSort);

}

}

---

그런데 아이폰 만 중복되게 호출이 됩니다.

고수님들 조언 부탁드립니다.

사파리---

988402489_1682501282.089.png

크롬--

988402489_1682501331.6095.png

|

답변 1개 / 댓글 4개

채택된 답변
+20 포인트
2023-04-26 (수) 19:39:04

중복 호출이 발생하는 이유는 didScroll 변수가 true일 때 setInterval이 계속해서 호출되기 때문입니다.

이를 해결하기 위해서는 infiniteScrollContent 함수 호출 후 didScroll 변수를 false로
초기화하는 것이 좋습니다.

또한, 이미 로드한 데이터의 경우 다시 호출하지 않도록 조건을 추가해주어야 합니다.
예를 들어, 이미 로드한 데이터가 애플아이폰인 경우 다음 데이터를 호출할 때 애플아이폰
이후의 데이터를 호출하도록 설정하는 것입니다.

아래는 수정된 소스 코드입니다.

Copy
var didScroll = false;
var loading = false;

$(window).on('scroll', function () {
    didScroll = true;
});

setInterval(function () {
    if (didScroll && !loading) {
        var bottomHeight = $(window).scrollTop() + $(window).height() + 600;
        var docHeight = $(document).height();
        if (bottomHeight > docHeight) {
            infiniteScrollContent();
            didScroll = false;
        }
    }
}, 250);

function infiniteScrollContent() {
    var total = $("#ajax_data > li.shopThumb").length;
    if (total >= _total_count) {
        didScroll = false;
    } else {
        var lastData = $("#ajax_data > li.shopThumb:last-child").data('name');
        console.log('스크롤 으로 리스트가져오기', total);
        get_shop_list(_count, total, _shopRegion, _shopSort, lastData);
        loading = true;
    }
}

function get_shop_list(count, total, region, sort, lastData) {
    $.ajax({
        url: "api/shop",
        type: "POST",
        data: {
            count: count,
            total: total,
            region: region,
            sort: sort,
            lastData: lastData
        },
        dataType: "json",
        success: function (result) {
            $("#ajax_data").append(result.data);
            loading = false;
        },
        error: function () {
            console.log('error');
        }
    });
}

챗GPT 답변입니다.

답변에 대한 댓글 4개

최고십니다. ^^
어제 해보니 안되더라구요
그런데,


데이터가져오후
인터발타임을 늘리니 해결이 되었네요

250 >> 600

1000으로 변경하는것이 맞을 까요?

setInterval(function () {
var bottomHeight = $(window).scrollTop() + $(window).height() + 600;

var docHeight = $(document).height();

if (didScroll) {
if (bottomHeight > docHeight) {
console.log('bottomHeight 전달', bottomHeight);
console.log('docHeight 전달', docHeight);
infiniteScrollContent();
didScroll = false;
}


}

}, 600 );
실행 간격이 600ms에서 1000ms로 더 길어지므로, 아이폰 등의 모바일 기기에서도 부담 없이 실행될 가능성이 높아집니다. 그러나 실행 간격이 너무 길어지면 사용자 경험에 부정적인 영향을 줄 수 있으므로, 실행 간격을 결정하는 데는 조금 더 고민이 필요합니다. 일반적으로는 500ms에서 1000ms 사이의 간격을 사용하는 것이 적절합니다.

챗GPT 답변입니다.
감사합니다. ^^~

답변을 작성하려면 로그인이 필요합니다.