javascript-setTimeout返回 [英] javascript - setTimeout return

查看:61
本文介绍了javascript-setTimeout返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要返回值,如何使用setTimeout

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;
}

推荐答案

首先,您对setTimeout的调用是错误的.您正在调用函数func,然后在setTimeout方法中使用结果.您的代码等效于:

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);      
});

func返回999时,您将执行setTimeout(999, 2000),这当然没有意义.要调用从setTimeout获取参数的函数,您需要一个进行该函数调用的函数:

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);
});

处理func中的返回值要复杂一些.正如稍后所调用的那样,您稍后必须处理返回值.通常,这是通过在返回值可用时调用的回调方法来完成的:

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);
}

这篇关于javascript-setTimeout返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆