How can I use setTimeout if I want to return a value
$.each(pCodes, function(index, pCode) {
setTimeout(func(parm1), 2000);
});
function func(in)
{
var value = 999;
return value;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First of all, your call to
setTimeoutis wrong. You are calling the functionfuncand then using the result in thesetTimeoutmethod. Your code is equivalent to:As
funcreturns999, you will be doingsetTimeout(999, 2000), which of course doesn’t make sense. To call a function that takes a parameter fromsetTimeoutyou need a function that makes that function call:To handle the return value from
funcis a bit more complicated. As it’s called later on, you have to handle the return value later on. Usually that is done with a callback method that is called when the return value is available: