Combining javascript timeout functions

Sorry for the basic level of the question, but js is definitely not my area of โ€‹โ€‹expertise. However, this is one of those questions that Google is hard to answer.

Basically I want to do a couple of things when the window is resized. I have some extra code that also stops the resize event twice.

The problem is that I duplicate bits of code, which, as an encoder, I know is wrong. The problem is that I do not know how to do it correctly. Here is my current duplicated code:

Event binding

    $(window).on("resize", resizeText);
    $(window).on("resize", resizeIndicator);

Functions

function resizeIndicator() {
    clearTimeout(id);
    id = setTimeout(updateIndicator, 200);
}

function resizeText() {
    clearTimeout(id);
    id = setTimeout(updateText, 200);
}

Thse are not duplicated but included for completeness:

function updateIndicator() {
    $tab = $(".tabs li.focus");

    if ($tab.length) {
        toggleIndicator($tab, true);
    }
}

function updateText() {
    $tabs = $(".tabs li:not(.indicator) a");

    $tabs.each(function () {
        $(this).toggleClass("two-line", this.scrollWidth > $(this).outerWidth());
    });
}
+4
source share
2 answers

- .

: http://jsbin.com/nugutujoli/1/edit?js,console,output

$(window).on("resize", resizeEvent);

var timeout;
function resizeEvent() {
    clearTimeout(timeout);
    timeout = setTimeout(function(){
      updateIndicator();
      updateText();
    }, 200);
}


function updateIndicator() {
   console.log("update indicator fired.");
}

function updateText() {
    console.log("update text fired.");
}
+1

, ? .

function createResizeCallback(resizeFunc) {
  var id;
  
  return function () {
    clearTimeout(id);
    id = setTimeout(resizeFunc, 200);
  }
}


$(window).on("resize", createResizeCallback(updateText));
$(window).on("resize", createResizeCallback(updateIndicator));


function updateIndicator() {
    console.log('updateIndicator');
}

function updateText() {
    console.log('updateText');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hide result
+3

All Articles