From cf374117177bbe2db55572d0274a77170dc96632 Mon Sep 17 00:00:00 2001 From: fofolee Date: Thu, 20 Feb 2025 21:57:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0setTimeout=E5=92=8CclearTimeo?= =?UTF-8?q?ut=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/lib/quickcommand.js | 16 +++++++++------- plugin/preload.js | 3 +++ src/plugins/monaco/types/common.d.ts | 3 +++ src/plugins/monaco/types/quickcommand.api.d.ts | 13 +++++++++++++ 4 files changed, 28 insertions(+), 7 deletions(-) diff --git a/plugin/lib/quickcommand.js b/plugin/lib/quickcommand.js index 2cb45ad..b8a371d 100644 --- a/plugin/lib/quickcommand.js +++ b/plugin/lib/quickcommand.js @@ -42,7 +42,6 @@ const quickcommand = { // setTimout 不能在 vm2 中使用,同时在 electron 中有 bug sleep: function (ms) { - var start = new Date().getTime(); try { // node 16.13.1 child_process.execSync(getSleepCodeByShell(ms), { @@ -50,23 +49,26 @@ const quickcommand = { windowsHide: true, }); } catch (ex) {} - var end = new Date().getTime(); - return end - start; + return; }, // 重写 setTimeout setTimeout: function (callback, ms) { - var start = new Date().getTime(); - child_process.exec( + const child = child_process.exec( getSleepCodeByShell(ms), { timeout: ms, }, () => { - var end = new Date().getTime(); - callback(end - start); + if (child.signalCode === "SIGKILL") return; + callback(); } ); + return child.pid; + }, + + clearTimeout: function (pid) { + kill(pid, "SIGKILL"); }, asyncSleep: async function (ms) { diff --git a/plugin/preload.js b/plugin/preload.js index 1dbf2ba..614cf72 100644 --- a/plugin/preload.js +++ b/plugin/preload.js @@ -137,6 +137,9 @@ let getSandboxFuns = () => { os, child_process, quickcomposer, + // timeout + setTimeout: quickcommand.setTimeout, + clearTimeout: quickcommand.clearTimeout, }; Object.keys(shortCodes).forEach((f) => { sandbox[f] = shortCodes[f]; diff --git a/src/plugins/monaco/types/common.d.ts b/src/plugins/monaco/types/common.d.ts index 3bc0b64..e254b83 100644 --- a/src/plugins/monaco/types/common.d.ts +++ b/src/plugins/monaco/types/common.d.ts @@ -88,3 +88,6 @@ declare var console: { log(message?: any): void, error(message?: any): void } + +declare var setTimeout: (callback: () => void, ms: number) => number; +declare var clearTimeout: (timeoutId: number) => void; diff --git a/src/plugins/monaco/types/quickcommand.api.d.ts b/src/plugins/monaco/types/quickcommand.api.d.ts index 47509a7..684ff6e 100644 --- a/src/plugins/monaco/types/quickcommand.api.d.ts +++ b/src/plugins/monaco/types/quickcommand.api.d.ts @@ -235,6 +235,19 @@ interface quickcommandApi { */ setTimeout(callback: () => void, ms); + /** + * 清除异步等待 + * + * @param timeoutId 等待的timeoutId + * ```js + * const timeoutId = quickcommand.setTimeout(()=>{ + * console.log('这条内容不会被打印') + * }, 2000) + * quickcommand.clearTimeout(timeoutId) + * ``` + */ + clearTimeout(timeoutId: number): void; + /** * async 等待 *