>  기사  >  웹 프론트엔드  >  JS 기능 조절 사용법

JS 기능 조절 사용법

php中世界最好的语言
php中世界最好的语言원래의
2018-03-13 17:25:271520검색

이번에는 JS 함수 조절 사용에 대해 알려드리겠습니다. JS 함수 조절 사용 시 주의사항은 무엇인가요? 실제 사례를 살펴보겠습니다.

함수 조절(throttle)

함수 조절은 실행 주기보다 크거나 같은 경우에만 함수가 실행되도록 예약하고, 주기 내의 호출은 실행되지 않도록 예약하는 것입니다. 그것은 마치 물 한 방울이 일정한 무게로 쌓인 후에 떨어지는 것과 같습니다.

시나리오:

창 크기 조정(크기 조정)

스크롤(스크롤)

미친 클릭(마우스다운)

구현:

function throttle(method, delay){    var last = 0;    return function (){        var now = +new Date();        if(now - last > delay){
            method.apply(this,arguments);
            last = now;
        }
    }
}document.getElementById('throttle').onclick = throttle(function(){console.log('click')},2000);

underscore 구현:

_.throttle = function(func, wait, options) {    var context, args, result;    var timeout = null;    var previous = 0;    if (!options) options = {};    var later = function() {
        previous = options.leading === false ? 0 : _.now();
        timeout = null;
        result = func.apply(context, args);        if (!timeout) context = args = null;
    };    return function() {        var now = _.now();        if (!previous && options.leading === false) previous = now;        //计算剩余时间
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;        //剩余时间小于等于0或者剩余时间大于等待时间(本地时间变动出现)
        if (remaining <= 0 || remaining > wait) {            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            previous = now;
            result = func.apply(context, args);            if (!timeout) context = args = null;
        } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(later, remaining);
        }        return result;
    };
};

기능 디바운스(디바운스)

함수 디바운스 즉, 이 함수는 상황을 자주 발생시켜야 하며, 여유 시간이 충분할 때 한 번만 실행됩니다. 버스 운전사는 버스에서 내리기 전에 모든 사람이 버스에 탈 때까지 기다리는 것 같습니다.

Scene:

Real-timesearch(keyup)

drag(mousemove)

implementation:

function debounce(method, delay){    var timer = null;    return function(){        var context = this,args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function(){
            method.apply(context, args);
        },delay);
    }
}document.getElementById(&#39;debounce&#39;).onclick = debounce(function(){console.log(&#39;click&#39;)},2000);

underscoreimplementation:

_.debounce = function(func, wait, immediate) {    var timeout, args, context, timestamp, result;    var later = function() {        var last = _.now() - timestamp;        if (last < wait && last >= 0) {
            timeout = setTimeout(later, wait - last);
        } else {
            timeout = null;            if (!immediate) {
                result = func.apply(context, args);                if (!timeout) context = args = null;
            }
        }
    };    return function() {
        context = this;
        args = arguments;
        timestamp = _.now();        var callNow = immediate && !timeout;        if (!timeout) timeout = setTimeout(later, wait);        if (callNow) {
            result = func.apply(context, args);
            context = args = null;
        }        return result;
    };
};

function throttling(throttle)과 function debounce(debounce)는 모두 지연을 통해 이루어집니다. 논리적 연산을 통해 성능을 향상시키는 방법은 프런트 엔드 최적화에서 일반적이고 중요한 솔루션입니다. 개념과 실제 적용을 통해 둘 사이의 차이점을 이해하고 필요에 따라 적절한 방법을 선택할 수 있습니다.

이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트기타 관련 기사를 주목하세요!

추천 도서:

JS 코드를 사용하여 사격 효과 만들기

H5 캔버스를 사용하여 사격 효과 만들기

위 내용은 JS 기능 조절 사용법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.