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 ...