2

I am trying to make a game, where the machine takes a while to respond, so the user actually knows the machine is 'deciding' its move. I need to use the setTimeout() method, but I want to specify a parameter to my function.

Example: setTimeout(myFunction('p'), 1000);. The problem is that when I specify the parameter, the function runs perfectly fine, but there´s no delay.

michaelmesser
  • 2,904
  • 2
  • 15
  • 35

3 Answers3

2

When you write setTimeout(myFunction('p'), 1000);, myFunction('p') is evaluated and then setTimeout(returnValueOfMyFunction, 1000) is evaluated.

This code will run the anonymous function at the correct time:

setTimeout(function (){myFunction('p')}, 1000);
michaelmesser
  • 2,904
  • 2
  • 15
  • 35
1

You can bind your function like this, so after the time, it will be executed:

setTimeout(myFunction.bind(this, 'p'), 1000);

thcerutti
  • 81
  • 2
1

Just wrap the function call with parameters in another parameterless function definition.

Example:

setTimeout(function() {
    myFunction('p');
}, 1000);
Meligy
  • 32,897
  • 11
  • 79
  • 103