Skip to content

Commit 8a38f54

Browse files
committed
async cleanup
The idea is to break the potentially expensive for-loops to potentially catch cancellation requests. After some reading `setImmediate` should be better suited for this than `await Promise.resolve()`
1 parent 7c5d789 commit 8a38f54

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

src/providers/document_colors.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as vscode from "vscode";
2-
import { Color8, hex, NAMED_COLORS, to_html, to_rgba32 } from "../utils/colors";
32
import { EXTENSION_PREFIX } from "../utils";
3+
import { Color8, NAMED_COLORS, hex, to_html, to_rgba32 } from "../utils/colors";
44

55
type Arg =
66
| ArgString
@@ -144,9 +144,7 @@ export class GDDocumentColorProvider implements vscode.DocumentColorProvider {
144144
if (color) {
145145
colors.push({ color, range });
146146
}
147-
// allow for early bail out
148-
await Promise.resolve();
149-
if (token.isCancellationRequested) {
147+
if (await isCancelled(token)) {
150148
return colors;
151149
}
152150
}
@@ -159,9 +157,7 @@ export class GDDocumentColorProvider implements vscode.DocumentColorProvider {
159157
if (color) {
160158
colors.push({ color, range });
161159
}
162-
// allow for early bail out
163-
await Promise.resolve();
164-
if (token.isCancellationRequested) {
160+
if (await isCancelled(token)) {
165161
return colors;
166162
}
167163
}
@@ -543,3 +539,10 @@ function parseCode(code: string): vscode.Color {
543539
function clamp(value: number, min: number, max: number): number {
544540
return Math.max(min, Math.min(value, max));
545541
}
542+
543+
/**
544+
* To be used within a loop to not monopolize the eventloop and check for cancellation.
545+
*/
546+
function isCancelled(token: vscode.CancellationToken): Promise<boolean> {
547+
return new Promise(resolve => setImmediate(() => resolve(token.isCancellationRequested)));
548+
}

0 commit comments

Comments
 (0)