Search code examples
javascriptarraysglobal-variableslocal-variables

export local array value to global value


I am trying to return the value of array by using console.log(array); it return empty value []. any suggestion is greatly appreciate it.

var array = [];
var maxLength = 3;
var delay = 250; //I shortened your delay
var ticker = {}; //I'll use this to simulate your ticker object

var looper = setInterval(function() { 
      ticker.BNBBTC = Math.random(); //populating your ticker property w/random value

      if (array.length < maxLength) {
         array.push(ticker.BNBBTC);
      } else {
         console.log("Stopping the looper.");
         clearInterval(looper);
         console.log("Here are the contents of array");
         console.log(array);
      }
}, delay);

Solution

  • Here's how you could do it with a callback

    const fn = callback => {
      var array = [];
      var maxLength = 3;
      var delay = 250; //I shortened your delay
      var ticker = {}; //I'll use this to simulate your ticker object
    
      var looper = setInterval(function() {
        ticker.BNBBTC = Math.random(); //populating your ticker property w/random value
    
        if (array.length < maxLength) {
          array.push(ticker.BNBBTC);
        } else {
          console.log("Stopping the looper.");
          clearInterval(looper);
          console.log("Here are the contents of array");
          callback(array);
        }
      }, delay);
    };
    fn(result => {
      console.log(result);
    })

    or with a Promise

    const fn = () => new Promise(resolve => {
      var array = [];
      var maxLength = 3;
      var delay = 250; //I shortened your delay
      var ticker = {}; //I'll use this to simulate your ticker object
    
      var looper = setInterval(function() {
        ticker.BNBBTC = Math.random(); //populating your ticker property w/random value
    
        if (array.length < maxLength) {
          array.push(ticker.BNBBTC);
        } else {
          console.log("Stopping the looper.");
          clearInterval(looper);
          console.log("Here are the contents of array");
          resolve(array);
        }
      }, delay);
    });
    fn().then(console.log)

    You'll notice with both of these methods there's no reason to "pollute" the global namespace - something that you should be avoiding as much as possible in modern javascript - the only global in either case is the const fn