John Ohara
John Ohara

Reputation: 2901

Consolidate javascript timeout functions

Sorry for the basic level of the question, but js definitely isn't my area of expertise. However, it's one of those questions that's difficult to Google an answer on.

I basically want to do a couple of things when the window is resized. I have a little bit of extra code that also stops the resize event firing twice.

The issue is that I'm duplicating bits of code, that as a coder, I know is wrong. The problem is I don't know how to go about making it right. Here's 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());
    });
}

Upvotes: 4

Views: 68

Answers (2)

Shadi Shaaban
Shadi Shaaban

Reputation: 1720

Declare your timeout id globally and use single handler.

Working demo: 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.");
}

Upvotes: 1

sielakos
sielakos

Reputation: 2404

So you want to avoid code duplication? No problem use higher order of function to create new function.

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>

Upvotes: 3

Related Questions