gazes12
@gazes12

Почему не работает throttle?

Здравствуйте.
Хочу реализовать throttle, ну у меня не получается.
/*Добавление  комментария*/

const throttle = (func, ms) =>{
    let isThrottle = false;
    return function(){
        if(isThrottle){
            return;
        }

        func.apply();
        isThrottle = true;

        setTimeout(() =>{
            isThrottle = false;
        }, ms);
    }
}

function addCommentFn(){
    const nameValue = create_name.val();
    const surnameValue = create_surname.val();
    const messageValue = create_message.val();

    $.ajax({
        url: '../php/comment.php',
        type: 'POST',
        dataType: 'json',
        data: {
            name: nameValue,
            surname: surnameValue,
            message: messageValue
        },

        success: function(result){
            if(result.comment){
                if(result.comment[0].user_id == result.user_id){
                    commentsBody.append(`
                    <div class="comments__item">
                        <div class="comments__people">
                            <div class="comments__name">${result.comment[0].name}</div>
                            <div class="comments__surname">${result.comment[0].surname}</div>
                        </div>
                        <div class="comments__control">
                            <p class="comments__change" id="${result.comment[0].id}">Изменить</p>
                            <p class="comments__delete" id="${result.comment[0].id}">Удалить</p>
                        </div>
                        <div class="comments__message">${result.comment[0].message}</div>
                    </div>
                    `);

                    commentsResults.html(`<div class="comments__result--succ comments__result">Комментарий отправлен!</div>`);
                    smoothResult();
                    
                    $("html, body").animate({
                        scrollTop: $(document).find(`.comments__change#${result.comment[0].id}`).offset().top
                    }, {
                        duration: 370,   // по умолчанию «400»
                        easing: "linear" // по умолчанию «swing»
                    });
                }
                
            }else if(result.errors){
                commentsResults.html(`<div class="comments__result--error comments__result">${result.errors}</div>`)
                smoothResult();
            }
        }
    });
}

sendButton.click((e) =>{
    e.preventDefault();
    throttle(addCommentFn, 5000);
});


Если написать просто:
return function(){
        func.apply();
    }


То тоже ничего не работает. Как это починить? Подскажите пожалуйста, очень долго не могу разобраться.
  • Вопрос задан
  • 119 просмотров
Решения вопроса 1
RAX7
@RAX7
throttle не вызывает переданную ему функцию, а лишь создает обертку для нее.
const throttledAddComment = throttle(addCommentFn, 5000);
sendButton.click((e) =>{
    e.preventDefault();
    throttledAddComment();
});
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы