[英]How to break an infinite loop inside a function on keystroke in Node.js?
I have an async function, stopwatch
.我有一个异步功能,
stopwatch
。 Upon calling, it starts to print time elapsed (in seconds) on every second.调用后,它开始每秒打印经过的时间(以秒为单位)。
How can I break this infinite loop and return time elapsed on keystroke ?我怎样才能打破这个无限循环并返回击键时间?
async function stopwatch() {
let elapsed = 0;
while (true) {
process.stdout.write(`Elapsed: ${elapsed} seconds`);
await sleep(1000);
elapsed++;
process.stdout.write("\u001b[2K\u001b[0E"); // clear current line and print at this line again next time
}
// on Keystroke: return time elapsed
}
export async function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
After learning a bit about EventEmitter
and with the keypress
package suggested by @rksh1997 , I come up with this solution:学习一些关于后
EventEmitter
并与keypress
包所建议@ rksh1997 ,我想出了这个解决方案:
const EventEmitter = require("events");
let keypress = require("keypress");
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
class StopWatch extends EventEmitter {
constructor() {
super();
this.elapsed = 0;
}
print() {
process.stdout.write("\u001b[2K\u001b[0E");
process.stdout.write(this.elapsed.toString());
}
}
async function runStopWatch(stopWatch) {
for (;;) {
if (stopWatch.stopped) break;
stopWatch.emit("tick");
await sleep(1000);
}
}
async function main() {
let stopWatch = new StopWatch(400);
stopWatch.on("tick", function () {
this.elapsed++;
this.print();
});
stopWatch.on("stop", function () {
this.stopped = true;
});
runStopWatch(stopWatch);
keypress(process.stdin);
process.stdin.on("keypress", function (ch, key) {
if (key && key.name == "q") { // hit 'q' to exit
stopWatch.emit("stop");
console.log("Elapsed:", stopWatch.elapsed);
process.stdin.pause();
}
});
process.stdin.setRawMode(true);
process.stdin.resume();
}
main()
How can I simplify my answer?我怎样才能简化我的答案? Is it possible to do this without using the EventEmitter?
是否可以在不使用 EventEmitter 的情况下执行此操作?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.