JavascriptsetInterval,如何给return一个值?

Javascript setInterval, how to return a value?

我一直无法尝试 return 来自 setInterval 函数的值,我听说这是不可能的。 return 还有其他方法吗?我需要 setInterval 函数每 10 秒递增一个变量,此时变量 'label_increment' 始终保持不变。

labels = [0];
label_increment = 1;

function getGPU(label_increment, labels){
    console.log("labelincrement:", label_increment);
    labels.push(label_increment);  //appends to array
    label_increment = label_increment + 1; //increments time
    console.log("labels:", labels);
    return label_increment
}

setInterval( function() { getGPU(label_increment, labels); }, 10000 );

最终目标是让标签数组读取 [1,2,3,4,5,6,7]。它需要每 10 秒递增一次,因为它用于实时图形。非常感谢任何可以帮助我的人!

因为getGPU函数是用参数label_increment定义的,所以这个函数里面的代码只引用参数,而不是之前定义的同名变量。

您可以通过 getGPU 函数执行 return,但您当前未使用该 return 值。

要在标签数组中获得所需的增量值,您可以重命名其中一个变量(函数参数或外部变量)并使用 return 值在每个时间间隔设置外部值:

labels = [0];
_label_increment = 1;

function getGPU(label_increment, labels){
    console.log("labelincrement:", label_increment);
    labels.push(label_increment);  //appends to array
    label_increment = label_increment + 1; //increments time
    console.log("labels:", labels);
    return label_increment
}

setInterval( function() { _label_increment = getGPU(_label_increment, labels); }, 500 );

...或者甚至不使用 label_increment 的参数,只引用最初声明的参数:

labels = [0];
label_increment = 1;

function getGPU(labels){
    console.log("labelincrement:", label_increment);
    labels.push(label_increment);  //appends to array
    label_increment = label_increment + 1; //increments time
    console.log("labels:", labels);
}

setInterval( function() { getGPU(labels); }, 500 );