0

I would like to display messages, and then hide them using the setTimeout function. So I would like the function I pass to the setTimeout function to take a parameter, the message to hide, so I can use 1 generic callback function. I tried the below code, but the label parameter is undefined when the callback executes.

var label = $('.js-a-label');
label.html('the message!');
setTimeout(hideMessage(label), 5000);

function hideMessage(label) {
  label.html('');
}
ab11
  • 19,770
  • 42
  • 120
  • 207

1 Answers1

1

In that code, you can just use label, as your function closes over it:

var label = $('.js-a-label');
label.html('the message!');
setTimeout(hideMessage, 5000);
function hideMessage() {
  label.html('');
}

In the general case where the function you're calling doesn't close over the information you want it to use, you have a couple of options:

  1. Add a function that does:

    var label = $('.js-a-label');
    label.html('the message!');
    setTimeout(function() { hideMessage(label); }, 5000);
    
  2. Use Function#bind (ES5+)

    var label = $('.js-a-label');
    label.html('the message!');
    setTimeout(hideMessage.bind(null, label), 5000);
    

    Function#bind returns a new function that, when called, calls the original with a specific this value (we don't need that, so I just used null above) and any arguments you give bind.

  3. Use $.proxy, which does much the same thing as Function#bind:

    var label = $('.js-a-label');
    label.html('the message!');
    setTimeout($.proxy(hideMessage, null, label), 5000);
    
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875