transfer data from local array to global variable

Need help with returning array values using console.log(array);, currently it's displaying empty value []. Any tips or suggestions would be greatly appreciated.

var array = [];
var maxLength = 3;
var delay = 250; //Shortened the delay
var ticker = {}; //Using this to simulate the ticker object

var looper = setInterval(function() { 
      ticker.BNBBTC = Math.random(); //Populating ticker property with 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);

Answer №1

Below is a method using a callback function

const fn = callback => {
  var array = [];
  var maxLength = 3;
  var delay = 250; //Reduced delay time
  var ticker = {}; 

  var looper = setInterval(function() {
    ticker.BNBBTC = Math.random(); 

    if (array.length < maxLength) {
      array.push(ticker.BNBBTC);
    } else {
      console.log("Stopping the looper.");
      clearInterval(looper);
      console.log("Array contents:");
      callback(array);
    }
  }, delay);
};
fn(result => {
  console.log(result);
})

Alternatively, you can use a Promise

const fn = () => new Promise(resolve => {
  var array = [];
  var maxLength = 3;
  var delay = 250; 
  var ticker = {};

  var looper = setInterval(function() {
    ticker.BNBBTC = Math.random(); 

    if (array.length < maxLength) {
      array.push(ticker.BNBBTC);
    } else {
      console.log("Stopping the looper.");
      clearInterval(looper);
      console.log("Array contents:");
      resolve(array);
    }
  }, delay);
});
fn().then(console.log)

In both methods, there's no need to clutter the global namespace - this should be avoided in modern javascript. The only global variable in both cases is const fn

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

attempting to eliminate on-screen buttons by hovering over the video

Is there a way to make my video play on loop like a GIF without the controls ever showing? I want it to have a seamless playback experience. Any ideas would be appreciated. P.s. Don't worry about any StackOverflow errors when running the snippet. Than ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...

The Map Function runs through each element of the array only one time

I'm new to JavaScript and experimenting with the map() function. However, I am only seeing one iteration in my case. The other elements of the array are not being displayed. Since this API generates random profiles, according to the response from the ...

Dealing with Sideways Overflow Using slideDown() and slideUp()

Attempting to use slideUp() and slideDown() for an animated reveal of page elements, I encountered difficulty when dealing with a relatively positioned icon placed outside the element. During these animations, overflow is set to hidden, resulting in my ico ...

Prevent automatic scrolling to anchors when using router.push() in Next.js

When using the latest version 10.2 of next, every time a URL with a hash is pushed to the router, next.js automatically jumps to the anchor element. import {useRouter} from 'next/router' router.push('/contact#about-us'); This behavior ...

Implementing AJAX requests in jQuery DataTable with ASP.NET MVC

For some time now, I have been using the jQuery DataTables 1.10.13 plugin. Recently, I encountered an issue related to the ajax data source for my HTML table. This is how I initialized jQuery DataTable inside Files.cshtml <script language="javascript" ...

Can we incorporate modulo into the loop?

I have a JavaScript function with HTML code inside. I need the ".one-card" div to repeat four times within each ".row" div. The ".row" div is being repeated in a foreach loop. I want to check if the result of modulo (4) is not equal to zero, then display t ...

Is there a way to determine if a browser's network activity is inactive?

Within an angularJS application, a noticeable delay can be experienced between the user and the server (potentially due to limited bandwidth), resulting in a wait time of approximately 2-500ms when loading a new page. I am considering implementing a metho ...

I updated the script to include a feature that automatically adds a leading zero to hours, minutes, and seconds if they are less than 10. However, for some reason, the output still doesn't show the leading zero

I have successfully created a countdown timer that works effectively. One of the conditions I added is to display leading zeros for hours, minutes, and seconds if they are less than 10. The desired format is like this (06 : 08 : 09) instead of (6 : 8 : 9 ...

Difficulty with CasperJS multi-select functionality

I am currently attempting to utilize CasperJS for choosing both options in a multiple select within an HTML form: <select id="bldgs" name="bldgs" multiple="multiple" size="6" autocomplete="off"> <option value="249759290">Southeast Financia ...

Unable to retrieve button value with material-ui package

My task requires me to retrieve the value of a button, as it contains an ID essential for further steps. Initially, I used a standard button with Bootstrap styling and everything functioned correctly. <button value={row.vacationRequestID} c ...

The Videojs controls are unresponsive to clicks

Having a strange issue with videojs. I've been attempting to load videojs in the same way as outlined in the documentation, using a dynamic video tag. videojs(document.getElementById('myVideo'), { "controls": true, "autoplay": false, "prelo ...

Hierarchy-based dynamic breadcrumbs incorporating different sections of the webpage

Currently in the process of developing a dynamic breadcrumb plugin with either jQuery or Javascript, however I am struggling to implement functionality that allows it to change dynamically as the page is scrolled. The goal is to have a fixed header elemen ...

React App with Material UI V1-beta Integration

I just installed the Create React App example from Material-UI.com. curl https://codeload.github.com/callemall/material-ui/tar.gz/v1-beta | tar -xz --strip=2 material-ui-1-beta/examples/create-react-app Upon installation, I encountered the following erro ...

Real-time functionality is not supported by Firebase functions

I've set up a firebase query within a method in VueJS: data: {this.todaysEvents}, methods : { getTodaysEvents (day) { this.todaysEvents = [] const events = db.ref('calendar') const query = events.orderByChild('da ...

SB Admin 2 menu with multiple levels does not collapse as expected

I'm in the process of integrating the menu from the sb admin 2 template into my Ruby on Rails application: As I gradually added components to test functionality, I successfully implemented the top and side nav bars. However, I encountered an issue wi ...

Loop through JSON data using jQuery for parsing

Here is the code snippet I have included below, which is a part of a larger code base: <html> <head> <style> #results{margin-top:100px; width:600px; border:1px solid #000000; background-color:#CCCCCC; min-height:200px;} </style> & ...

Steps for adjusting the position of this div in relation to the main container

Apologies in advance for my lack of HTML skills. I am struggling with a page layout issue. I have a website at . When the window is resized, the ads div on the right side overlaps the main container. What I would like to achieve is to make this ads div re ...

Tips for integrating the AJAX response into a Sumo Select dropdown menu

I am currently using Sumoselect for my dropdowns, which can be found at . The dropdowns on my page are named as countries, state, and cities. The countries are shown in the dropdown, and based on the country selected, the corresponding state name should a ...

The input field is failing to capture the final character entered

Is there a way to store all input files in a single object and use the information in a graph? Currently, when I enter the first character, it creates an empty object, so the last character I enter is not captured in the object. Any suggestions on how to ...