简体   繁体   English

使用 Node.js 暂停控制台输出

[英]Pause console output using Node.js

I am trying to create a time display (h:mm:ss) with just using the console and not on a web page.我正在尝试仅使用控制台而不是在网页上创建时间显示 (h:mm:ss)。 The time should be set initially and from there display the time as it changes.最初应设置时间,然后在更改时显示时间。

When using the output console (in the web browser) or in vscode, is it possible for js or node.js, while printing thousands/multiple outputs to have a delay between each output being printed in the console without using an extension?当使用输出控制台(在 Web 浏览器中)或在 vscode 中时,js 或 node.js 是否有可能在打印数千/多个输出时在控制台中打印的每个输出之间存在延迟而不使用扩展?

Here's an example of printing the current time to the console every 1 second:下面是每 1 秒将当前时间打印到控制台的示例:

 // setInterval() executes the given function on a given time interval setInterval(() => { console.log(new Date().toTimeString()); // function to execute }, 1000) // execute every 1000 ms

You can also print your own counter:您还可以打印自己的计数器:

 let secondsElapsed = 0 setInterval(() => { console.log(`seconds elapsed = ${secondsElapsed}`); secondsElapsed++; }, 1000)

Here is how to accomplish what you seem to be asking:以下是如何完成您似乎要求的内容:

 const clockTick = (callback) => { const tick = () => { const now = Date.now(); callback(now); setTimeout(tick, 1000 - (now % 1000)); } tick(); } clockTick(timestamp => { const date = new Date(timestamp); const hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); console.log(`${hours}:${minutes}:${seconds}`); });

The accepted answer isn't correct.接受的答案不正确。 IMO, we should implement a queue or something similar in order to achieve "delay between each output". IMO,我们应该实现一个队列或类似的东西,以实现“每个输出之间的延迟”。 I find this question interesting so I implement this code for some fun (which use promise chain as a simple queue):我觉得这个问题很有趣,所以我为了一些乐趣而实现了这段代码(使用承诺链作为一个简单的队列):

const callNext = (function () {
  let queueChain = Promise.resolve();

  // Called after previous command (1 second by default)
  function callNext(func, delay = 1000) {
    queueChain = queueChain.then(() => {
      return new Promise((res) => {
        setTimeout(() => {
          func();
          res();
        }, delay);
      });
    });
  }

  return callNext;
})();

callNext(() => {
  console.log('run after 3s')
}, 3000);

callNext(() => {
  console.log('run after the above 3s')
}, 3000);

callNext(() => {
  console.log('run after the above 1s by default')
});

we can create a simple logger using the above callNext for cleaner syntax:我们可以使用上面的callNext创建一个简单的记录器以获得更清晰的语法:

const logger = (function () {
  function createLogFn(name) {
    return function (...args) {
      let delay = 1000;

      // take the last argument as "delay" param
      if (typeof args[args.length -1] === 'number') {
        delay = args.pop();
      }

      callNext(() => {
        console[name](`${name.toUpperCase()} [${(new Date().toISOString())}]: `, ...args);
      }, delay);
    };
  }

  const logger = {
    log: createLogFn('log'),
    info: createLogFn('info'),
    debug: createLogFn('debug'),
    error: createLogFn('error'),
  }
  return logger;
})();

logger.log('run after 3s', 3000);
logger.log('run after the above 3s', 3000);
logger.log('run after the above 1s');

logger.info('final run after the above 2s', 2000);

Check it out: https://jsfiddle.net/pk5oqfxa/看看: https : //jsfiddle.net/pk5oqfxa/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM