Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - javascript - setTimeout return

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, your call to setTimeout is wrong. You are calling the function func and then using the result in the setTimeout method. Your code is equivalent to:

$.each(pCodes, function(index, pCode) {
  var temp = func(parm1);
  setTimeout(temp, 2000);      
});

As func returns 999, you will be doing setTimeout(999, 2000), which of course doesn't make sense. To call a function that takes a parameter from setTimeout you need a function that makes that function call:

$.each(pCodes, function(index, pCode) {
  setTimeout(function() { func(parm1); }, 2000);
});

To handle the return value from func is 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:

var callback = function(value) {
  // Here you can use the value.
};
$.each(pCodes, function(index, pCode) {
  setTimeout(function() { func(parm1, callback); }, 2000);
});

function func(in, callback) {
  var value = 999;
  callback(value);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...