Skip to content

Commit 818ca34

Browse files
committedNov 1, 2024
Fix frame handling
1 parent 5117dfb commit 818ca34

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed
 

‎index.js

+11-3
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ class Ora {
1313
#linesToClear = 0;
1414
#isDiscardingStdin = false;
1515
#lineCount = 0;
16-
#frameIndex = 0;
16+
#frameIndex = -1;
17+
#lastSpinnerFrameTime = 0;
1718
#options;
1819
#spinner;
1920
#stream;
@@ -109,7 +110,7 @@ class Ora {
109110
}
110111

111112
set spinner(spinner) {
112-
this.#frameIndex = 0;
113+
this.#frameIndex = -1;
113114
this.#initialInterval = undefined;
114115

115116
if (typeof spinner === 'object') {
@@ -222,14 +223,21 @@ class Ora {
222223
}
223224

224225
frame() {
226+
// Ensure we only update the spinner frame at the wanted interval,
227+
// even if the render method is called more often.
228+
const now = Date.now();
229+
if (this.#frameIndex === -1 || now - this.#lastSpinnerFrameTime >= this.interval) {
230+
this.#frameIndex = ++this.#frameIndex % this.#spinner.frames.length;
231+
this.#lastSpinnerFrameTime = now;
232+
}
233+
225234
const {frames} = this.#spinner;
226235
let frame = frames[this.#frameIndex];
227236

228237
if (this.color) {
229238
frame = chalk[this.color](frame);
230239
}
231240

232-
this.#frameIndex = ++this.#frameIndex % frames.length;
233241
const fullPrefixText = (typeof this.#prefixText === 'string' && this.#prefixText !== '') ? this.#prefixText + ' ' : '';
234242
const fullText = typeof this.text === 'string' ? ' ' + this.text : '';
235243
const fullSuffixText = (typeof this.#suffixText === 'string' && this.#suffixText !== '') ? ' ' + this.#suffixText : '';

‎test.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,10 @@ test('reset frameIndex when setting new spinner', async t => {
267267
},
268268
});
269269

270+
t.is(spinner._frameIndex, -1);
271+
270272
spinner.render();
271-
t.is(spinner._frameIndex, 1);
273+
t.is(spinner._frameIndex, 0);
272274

273275
spinner.spinner = {frames: ['baz']};
274276
spinner.render();

0 commit comments

Comments
 (0)
Please sign in to comment.