代码之家  ›  专栏  ›  技术社区  ›  mbilyanov

如何构建一个在javascript中不断发出数字的函数?

  •  0
  • mbilyanov  · 技术社区  · 6 年前

    有没有办法建立一个函数,它将在后台运行,并将不断产生一个随机数。

    但是,其余代码将继续运行,其他位应该能够连接到该函数并随时获取随机数。

    // So this runs and keeps running forever.
    function emit(){
        while(true){    
            return Math.random().toFixed(4);
        }
    };
    
    // This bit is capable of tapping into the emitted data and return
    // the values at any time.
    function listen(){
         console.log(emit);
    };
    

    可以不用 setInterval() ?

    目的是把它输入websocket。

    wss.on('connection', () => {
        wss.clients.forEach(function(client) {
            // Maybe a bit like fetch the current result of the emitter
            // and send to the client.  
            client.send(*/ listen and stream to the client */);
        }
    }
    

    0.2344, 0.9425, 0.5385, 0.2357 ...
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Jonas Wilms    6 年前

    有没有办法建立一个函数,它将在后台运行,并将不断产生一个随机数。

    是的,这是可能的,启动一个新线程 WebWorkers spawnProcess 在NodeJS上,然后运行 while(true)

    但是,其余代码将继续运行,其他位应该能够连接到该函数并在任何时候获取随机数

    您可以从另一个线程将数据写入SharedBuffer,并随时从主进程读取它。


    这有道理吗?

    如果你想无缘无故地浪费能源和加工时间,这当然是有道理的。如果你真的需要的话,不仅仅是生成数据。