美文网首页
防抖节流

防抖节流

作者: overflow_hidden | 来源:发表于2019-07-17 15:37 被阅读0次
    function debounce(fn, interval = 300) {
        let timeout = null;
        return function () {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                fn.apply(this, arguments);
            }, interval);
        };
    }
    
    $('input.user-name').on('input', debounce(function () {
        $.ajax({
            url: `https://just.com/check`,
            method: 'post',
            data: {
                username: $(this).val(),
            },
            success(data) {
                if (data.isRegistered) {
                    $('.tips').text('该用户名已被注册!');
                } else {
                    $('.tips').text('恭喜!该用户名还未被注册!');
                }
            },
            error(error) {
                console.log(error);
            },
        });
    }));
    
    function throttle(fn, interval = 300) {
        let canRun = true;
        return function () {
            if (!canRun) return;
            canRun = false;
            setTimeout(() => {
                fn.apply(this, arguments);
                canRun = true;
            }, interval);
        };
    }
    
    $(window).on('scroll', throttle(function () {
        // 判断是否滚动到底部的逻辑
        let pageHeight = $('body').height(),
            scrollTop = $(window).scrollTop(),
            winHeight = $(window).height(),
            thresold = pageHeight - scrollTop - winHeight;
        if (thresold > -100 && thresold <= 20) {
            console.log('end');
        }
    }));
    

    相关文章

      网友评论

          本文标题:防抖节流

          本文链接:https://www.haomeiwen.com/subject/ydgtgqtx.html