Skip to content

Commit 4de7ea8

Browse files
Limit progress callbacks (#30)
Set it to a reasonable value by default that gives somewhat smooth progress bars.
1 parent 66b4d89 commit 4de7ea8

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

lib/usb.ts

+24-1
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ export class MicrobitWebUSBConnection
204204
options: {
205205
partial: boolean;
206206
progress: (percentage: number | undefined) => void;
207+
miniumProgressIncrement: number;
207208
},
208209
): Promise<void> {
209210
this.flashing = true;
@@ -232,6 +233,7 @@ export class MicrobitWebUSBConnection
232233
options: {
233234
partial: boolean;
234235
progress: (percentage: number | undefined, partial: boolean) => void;
236+
miniumProgressIncrement: number;
235237
},
236238
): Promise<void> {
237239
this.log("Stopping serial before flash");
@@ -243,7 +245,10 @@ export class MicrobitWebUSBConnection
243245
}
244246

245247
const partial = options.partial;
246-
const progress = options.progress || (() => {});
248+
const progress = rateLimitProgress(
249+
options.miniumProgressIncrement ?? 0.0025,
250+
options.progress || (() => {}),
251+
);
247252

248253
const boardId = this.connection.boardSerialInfo.id;
249254
const boardVersion = boardId.toBoardVersion();
@@ -516,3 +521,21 @@ const enrichedError = (err: any): DeviceError => {
516521
}
517522
}
518523
};
524+
525+
const rateLimitProgress = (
526+
miniumProgressIncrement: number,
527+
callback: (value: number | undefined, partial: boolean) => void,
528+
) => {
529+
let lastCallValue = -1;
530+
return (value: number | undefined, partial: boolean) => {
531+
if (
532+
value === undefined ||
533+
value === 0 ||
534+
value === 1 ||
535+
value >= lastCallValue + miniumProgressIncrement
536+
) {
537+
lastCallValue = value ?? -1;
538+
callback(value, partial);
539+
}
540+
};
541+
};

src/demo.ts

+2
Original file line numberDiff line numberDiff line change
@@ -209,12 +209,14 @@ const createFlashSection = (): Section => {
209209
if (file) {
210210
const text = await file.text();
211211
if (connection.flash) {
212+
console.time("flash");
212213
await connection.flash(createUniversalHexFlashDataSource(text), {
213214
partial: true,
214215
progress: (percentage: number | undefined) => {
215216
console.log(percentage);
216217
},
217218
});
219+
console.timeEnd("flash");
218220
}
219221
}
220222
},

0 commit comments

Comments
 (0)