Creating a continuous number-emitting function in JavaScript

Is it feasible to construct a function that operates in the background, continuously generating a random number while allowing other parts of the code to access and retrieve the generated numbers?

// The following function runs indefinitely.
function emit(){
    while(true){    
        return Math.random().toFixed(4);
    }
};

// This segment can tap into the emitted data and fetch
// the values whenever needed.
function listen(){
     console.log(emit);
};

Can this be achieved without relying on setInterval()?

--- EDIT ---

The ultimate goal is to use this for feeding data into a websocket.

wss.on('connection', () => {
    wss.clients.forEach(function(client) {
        // Perhaps similar to fetching the current result from the emitter
        // and sending it to the client.  
        client.send(*/ listen and stream to the client */);
    }
}

This way, the client receives an ongoing flow of numbers:

0.2344, 0.9425, 0.5385, 0.2357 ...

Answer №1

Is there a feasible method of creating a function that operates in the background and consistently generates random numbers?

Absolutely, you can achieve this by initiating a new thread using WebWorkers in web browsers or spawnProcess in NodeJS. Once set up, incorporate a while(true) loop to continuously generate random numbers.

Nevertheless, it is crucial that the main code can concurrently run while having access to this function to retrieve the random number at any given moment.

To facilitate this, consider storing the data in a SharedBuffer from the secondary thread and retrieve it as needed from the primary process.


Yet, the fundamental question emerges:

Does this approach hold merit?

If dedicating unnecessary energy and processing time aligns with your objectives, then this method makes perfect sense. However, if efficiency is a priority, generating random data only when necessary would be more advisable.

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

Creating customized JavaScript using jQuery for Drupal 7 Form API

Currently, I am working on developing a custom form using Drupal 7 with form API and a tableselect that includes checkboxes. I have some specific constraints for selecting the checkboxes that I intend to implement using jQuery. I created a function for han ...

Track the amount of time a particular user spends on the website and save the data in a MySQL database

I am looking to track the amount of time each user spends on my page in seconds. For example, if User X enters the site at 8:00 am and leaves at 8:15 am, I want to add 900 seconds to their account. Let's say the user has visited multiple times before ...

Script to populate database using Mongoose gets stuck

I'm currently dealing with the following script: const db = require('../db') const User = require('../models/user') db.on('error', console.error.bind(console, 'MongoDB connection error:')) const main = async ...

The Chrome equivalent of -moz-user-focus

We have a custom model dialog control that we use for all popups on our web pages. When this dialog is initialized, we use jQuery expose to gray out the rest of the page. To prevent selection on the grayed-out area, we apply the following styles to the mas ...

Access the outcome by utilizing a for loop

Within my code, I am utilizing both a function and a loop: var songs = Musics.searchSongs(query).then(function(rs) { return rs; }); for (var i = 0; i < songs.length; i++) { console.log(songs[i]); } I am now looking for a way to execute the ...

Finding a workaround for the absence of a leftToggle feature in ListItem component of Material-UI

Is there a way to move the toggle element to the other side in Material-UI's listItem without using the leftToggle option? The documentation does not specify a leftToggle attribute, so I am looking for alternative solutions. I would like to align the ...

Problem encountered with a selection menu

I'm experiencing some trouble with the dropdown menu. Whenever I try to move the mouse to access the dropdown menu, it seems unresponsive. I attempted adjusting the padding on a line of code but ended up moving the entire line instead. Here is the cod ...

Enhance user experience with Jqgrid hyperlinked user format

I am currently utilizing jqgrid with JSON data that is structured as follows: {"my_id" : 12345, "doc_number" : 9786} My objective is to implement an hlink formatter that displays the doc_number, while passing the my_id as a parameter to my JavaScript func ...

Combining array elements into sets of n

I am facing a challenge with an array manipulation task. let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; My goal is to divide this array into a specified number of smaller arrays such that each new array contains the same number of elements ...

Utilizing AngularJS to incorporate a global scope function within another function

I have a specific AngularJS function named editlocation that triggers a Modal window to edit three data points. Following this process, I aim to execute plotmarkers, which is utilized in another scenario of an ng-click. Despite attempting different approa ...

Restrict the vertical camera rotation

Utilizing JSModeler for showcasing OBJ files. The software integrates THREE.JS and generates a PerspectiveCamera. My goal is to restrict the camera's Y-axis movement to prevent it from going beneath the object. While I am familiar with achieving this ...

The compiled JavaScript is getting messed up by the Grunt build process

I have taken over a project that was incomplete from the beginning. I am facing issues with the deployment as the grunt task is not working correctly, even after following the overrides specified here. The generated vendor.js file seems to be causing error ...

Tips for customizing settings and implementing an event listener for Semantic UI sidebar

Looking to customize the behavior of a Semantic UI sidebar by preventing the page from being dimmed when the sidebar is shown and ensuring that the onShow event is triggered only when the sidebar is fully visible. $("#sidebar").sidebar onShow: => @ ...

JS custom scrollbar thumb size issues in relation to the scroll width of the element

I recently implemented a custom scrollbar for a component on my website. To determine the length of the scrollbar thumb, I use the formula viewportWidth / element.scrollWidth;. This provides me with a percentage value that I then apply to the thumb elemen ...

Troubleshooting imagejpeg() Function Failure in PHP Server

I've been working on implementing image cropping functionality for my website. I've managed to send an array of cropped image dimensions (x, y, width, height) to my PHP script. On my localhost, the script successfully crops the image, but unfort ...

Steps for initiating a new dispatch once the previous one has concluded

Thank you for taking the time to read my query and offering your assistance. I apologize in advance for any language errors. I am currently working with redux and redux-thunk, and I am looking to trigger multiple dispatch actions in redux sequentially. Sp ...

Utilizing Reactjs to dynamically populate Bootstrap grids: A step-by-step guide

Is there a more efficient way to display match stats boxes using ReactJS and Bootstrap grids? I currently have 16 grids set up in a 4X4 layout, each row containing 4 columns. Instead of manually creating 16 match stats boxes, is there a way to dynamically ...

AngularJS - Choose and establish initial values for Editing or Creating New Items

My first project involving AngularJS has left me a bit stuck when it comes to using the select list. I need to either set the default value to the first option for a new entry, or if it's an edit, select the appropriate value. In my form, there are t ...

What could be causing the Access-Control-Allow-Origin error to appear when attempting to access a page using ajax?

As I attempt to utilize Ajax to retrieve data from my website using a script that should be able to execute from any location, the Ajax code within my script is structured like this: var ajax = new XMLHttpRequest(); ajax.open('GET', 'http:/ ...

How to remove a material form field in a dynamic form with a single parameter

Deleting the single param mat form field proves to be a challenge, but deleting the multiple param form field is successful. <ng-container *ngSwitchCase="'input'"> <ng-container *ngIf="param.allowMultiple; else singlePar ...