-3

I need a delay before executing certain function in java script. I could use setTimeout but the problem is I have two variables passed to function. I need to syntax for setTimeout in this case.Can anyone help?

jeja
  • 52
  • 11

3 Answers3

5

In any modern JavaScript environment, you can include arguments after the interval:

setTimeout(foo, 2000, 'a', 'b');

That will call foo('a', 'b') after 2000ms.

In obsolete JavaScript environments (such as those in some obsolete browsers), you have to use a wrapper function:

setTimeout(function() {
    foo('a', 'b');
}, 2000);

but, there's a big difference between those two: In the first case, any expressions are evaluated when you call setTimeout and the result of that evaluation is what gets sent to setTimeout and ultimately to foo, whereas with the wrapper function, the evaluation happens after the delay, later, when foo is called.

You can get the same evaluation behavior as the first by using Function#bind:

setTimeout(foo.bind(null, 'a', 'b'), 2000);

Here's an example of the difference:

var a = 1;
setTimeout(foo, 100, a);            // foo will show 1
a = 2;
setTimeout(foo.bind(null, a), 100); // foo will show 2
setTimeout(function() {
    foo(a);                         // foo will show 3 even though
                                    // we set it *after* scheduling
                                    // the call
}, 100);
a = 3;

function foo(value) {
  console.log(value);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • beat me by 4 seconds :( – brennanenanen Jul 17 '17 at 10:11
  • 1
    @Albzi: Meh, SO's about building a source of knowledge. The real problem (and the reason I'm moving this answer elsewhere) is that the question is a duplicate. *Edit:* Actually no, [this answer](https://stackoverflow.com/a/17557081/157247) has it covered. I'll leave this here as the other answers are too vague and don't discuss important aspects, but I'll CW it. – T.J. Crowder Jul 17 '17 at 10:15
  • 1
    I agree with you! As a side note - I did not mean to come across confrontational as I think it does unintentionally as I read it back, I just meant that the effort of this question is so low quality that it should have been improved or voted to close. Sorry if I came across rude! – Albzi Jul 17 '17 at 10:20
  • 1
    @Albzi: No worries. :-) – T.J. Crowder Jul 17 '17 at 10:20
1
setTimout(function () {
  yourfunction(variable1, variable2)
}, delay)
brennanenanen
  • 409
  • 5
  • 10
1
function something(val1, val2){
 return val1+val2;
}
setInterval(function(){
 something(23,32);
}, 50);
cymruu
  • 2,808
  • 2
  • 11
  • 23