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('');
}
1
  • below sample would help function consoleIt(param){ console.log(param); } setTimeout(function(){ consoleIt("hello") },3000); Commented Jun 11, 2015 at 15:37

1 Answer 1

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);
    
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.