Search code examples
javascriptreturnsetinterval

Javascript setInterval, how to return a value?


I have been having trouble trying to return a value from a setInterval function, I have heard this isn't possible. Is there another way to return a value? I need the setInterval function to increment a variable every 10 seconds, at the moment the variable 'label_increment' always stays the same.

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

The end goal is for the labels array to read [1,2,3,4,5,6,7]. It needs to be incremented every 10 seconds because it is for a real time graph. Thank you very much to anybody that can assist me!


Solution

  • Because the getGPU function is defined with an argument label_increment, the code inside this function refers only to the argument, not the variable defined before with the same name.

    You can do a return from the getGPU function, but you are not currently using that return value.

    To achieve the desired incremented values in the labels array you could rename one of the variables (either the function argument, or the outside one) and use the return value to set the outside value at every interval:

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

    ...or not even use an argument for label_increment and only refer to the initially declared one:

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