genbodev
3/13/2018 - 10:14 AM

deBounce

Чтобы снизить нагрузку на браузер при вычислении, можно использовать метод deBounce. В частности это снизит нагрузку при расчетах, когда нужно изменить размер браузера

/**
  * Function that prohibits exaggerating the performance of another function in order to improve performance
  * @param func - Function, which should be prohibited from exaggeration
  * @param wait - How long to wait in ms before the function can be executed again
  * @param immediate - true, if you need to execute immediately
  * @returns {Function}
*/
function deBounce(func, wait, immediate) {
  let timeout;
  return function () {
    let context = this, args = arguments;
    let later = function () {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    let callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

// func - функция, которая может вызвать нагрузку
// wait - пауза между обработкой функции вв мс
// immediate - вызов без пауз через подачу true

// Использование

let prevInnerWidth, innerWidth;
if (!prevInnerWidth) {
  prevInnerWidth = window.innerWidth;
}
innerWidth = window.innerWidth;

// Resize
$(window).resize(function () {
  (deBounce(function () {
    // Далее функционал, вызывающий нагрузку
    generateTable(currentActive, getActiveData(currentActive), 'table-' + currentActive + '-wrapper');
      // Можем что то сделать отдельно, например, если изменилась ширина браузера
      if (window.innerWidth !== prevInnerWidth) {
        $('#app-trading-conditions-search').val('');
        prevInnerWidth = innerWidth;
      }
    }, 100))();
});