John Ohara John Ohara - 6 months ago 25
jQuery Question

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());
});
}

Answer

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.");
}
Comments