0
# Timers
1
2
Integrated timer functionality for measuring operation duration with automatic labeling and formatted output. Timers provide a convenient way to measure and log execution time for operations with clear visual indicators.
3
4
## Capabilities
5
6
### Timer Management
7
8
Start and stop timers with automatic or custom labeling.
9
10
```javascript { .api }
11
/**
12
* Start a timer with optional custom label
13
* @param label - Optional timer label (auto-generated if not provided)
14
* @returns The timer label used for this timer
15
*/
16
function time(label?: string): string;
17
18
/**
19
* Stop a timer and display the elapsed time
20
* @param label - Optional timer label (uses most recent unlabeled timer if not provided)
21
* @returns Object containing the timer label and elapsed time in milliseconds, or undefined if timer not found
22
*/
23
function timeEnd(label?: string): {label: string, span: number} | undefined;
24
```
25
26
### Basic Timer Usage
27
28
Simple timer operations with automatic labeling.
29
30
**Usage Examples:**
31
32
```javascript
33
const signale = require('signale');
34
35
// Start timer with auto-generated label
36
const label1 = signale.time();
37
// Output: ▶ timer_0 Initialized timer...
38
39
const label2 = signale.time();
40
// Output: ▶ timer_1 Initialized timer...
41
42
// Simulate some work
43
setTimeout(() => {
44
// End most recent timer (timer_1)
45
const result1 = signale.timeEnd();
46
// Output: ◼ timer_1 Timer run for: 1.02s
47
console.log(result1); // {label: 'timer_1', span: 1020}
48
49
// End specific timer (timer_0)
50
const result2 = signale.timeEnd('timer_0');
51
// Output: ◼ timer_0 Timer run for: 1.15s
52
console.log(result2); // {label: 'timer_0', span: 1150}
53
}, 1000);
54
```
55
56
### Custom Timer Labels
57
58
Use meaningful labels for better organization and readability.
59
60
**Usage Examples:**
61
62
```javascript
63
const signale = require('signale');
64
65
// Start named timers
66
signale.time('database-query');
67
// Output: ▶ database-query Initialized timer...
68
69
signale.time('file-processing');
70
// Output: ▶ file-processing Initialized timer...
71
72
signale.time('api-request');
73
// Output: ▶ api-request Initialized timer...
74
75
// End specific timers by label
76
setTimeout(() => {
77
signale.timeEnd('database-query');
78
// Output: ◼ database-query Timer run for: 245ms
79
80
signale.timeEnd('file-processing');
81
// Output: ◼ file-processing Timer run for: 1.35s
82
83
signale.timeEnd('api-request');
84
// Output: ◼ api-request Timer run for: 892ms
85
}, 1000);
86
```
87
88
### Timer Return Values
89
90
Capture and use timer results programmatically.
91
92
**Usage Examples:**
93
94
```javascript
95
const signale = require('signale');
96
97
async function processData() {
98
const timerLabel = signale.time('data-processing');
99
100
// Simulate data processing
101
await new Promise(resolve => setTimeout(resolve, 1500));
102
103
const result = signale.timeEnd(timerLabel);
104
105
if (result) {
106
const { label, span } = result;
107
108
if (span > 1000) {
109
signale.warn(`Operation ${label} took ${span}ms - consider optimization`);
110
} else {
111
signale.success(`Operation ${label} completed efficiently in ${span}ms`);
112
}
113
}
114
}
115
116
processData();
117
// Output: ▶ data-processing Initialized timer...
118
// ◼ data-processing Timer run for: 1.50s
119
// ⚠ warning Operation data-processing took 1500ms - consider optimization
120
```
121
122
### Multiple Timer Management
123
124
Handle multiple concurrent timers with different strategies.
125
126
**Usage Examples:**
127
128
```javascript
129
const signale = require('signale');
130
131
// Start multiple timers
132
const dbTimer = signale.time('database');
133
const cacheTimer = signale.time('cache');
134
const autoTimer1 = signale.time(); // timer_0
135
const autoTimer2 = signale.time(); // timer_1
136
137
setTimeout(() => {
138
// End timers in different order
139
signale.timeEnd('cache'); // End by name
140
signale.timeEnd(); // End most recent auto-timer (timer_1)
141
signale.timeEnd('database'); // End by name
142
signale.timeEnd(); // End remaining auto-timer (timer_0)
143
}, 800);
144
145
// Output:
146
// ▶ database Initialized timer...
147
// ▶ cache Initialized timer...
148
// ▶ timer_0 Initialized timer...
149
// ▶ timer_1 Initialized timer...
150
// ◼ cache Timer run for: 800ms
151
// ◼ timer_1 Timer run for: 800ms
152
// ◼ database Timer run for: 800ms
153
// ◼ timer_0 Timer run for: 800ms
154
```
155
156
### Timer Formatting
157
158
Timers automatically format display based on duration.
159
160
**Usage Examples:**
161
162
```javascript
163
const signale = require('signale');
164
165
// Short duration (milliseconds)
166
signale.time('short');
167
setTimeout(() => {
168
signale.timeEnd('short');
169
// Output: ◼ short Timer run for: 150ms
170
}, 150);
171
172
// Medium duration (seconds with decimals)
173
signale.time('medium');
174
setTimeout(() => {
175
signale.timeEnd('medium');
176
// Output: ◼ medium Timer run for: 2.35s
177
}, 2350);
178
179
// Long duration (seconds with decimals)
180
signale.time('long');
181
setTimeout(() => {
182
signale.timeEnd('long');
183
// Output: ◼ long Timer run for: 15.67s
184
}, 15670);
185
```
186
187
### Timer Error Handling
188
189
Handle cases where timers don't exist or have issues.
190
191
**Usage Examples:**
192
193
```javascript
194
const signale = require('signale');
195
196
// Try to end non-existent timer
197
const result = signale.timeEnd('non-existent');
198
console.log(result); // undefined (no output, no error)
199
200
// Try to end timer when no auto-timers exist
201
const result2 = signale.timeEnd();
202
console.log(result2); // undefined (no output, no error)
203
204
// Start and end the same timer twice
205
signale.time('duplicate-test');
206
const first = signale.timeEnd('duplicate-test');
207
console.log(first); // {label: 'duplicate-test', span: ...}
208
209
const second = signale.timeEnd('duplicate-test');
210
console.log(second); // undefined (timer already ended)
211
```
212
213
### Scoped Timer Inheritance
214
215
Timers work with scoped loggers and inherit timer state.
216
217
**Usage Examples:**
218
219
```javascript
220
const signale = require('signale');
221
222
// Start timer on main instance
223
signale.time('main-timer');
224
225
// Create scoped logger - inherits timer state
226
const scoped = signale.scope('module');
227
228
// Timer state is shared
229
scoped.timeEnd('main-timer');
230
// Output: [module] › ◼ main-timer Timer run for: 1.23s
231
232
// Start timer on scoped logger
233
scoped.time('scoped-timer');
234
235
// End from main instance - timers are shared
236
signale.timeEnd('scoped-timer');
237
// Output: ◼ scoped-timer Timer run for: 456ms
238
```
239
240
### Practical Timer Patterns
241
242
Common patterns for using timers in applications.
243
244
**Usage Examples:**
245
246
```javascript
247
const signale = require('signale');
248
249
// Function timing wrapper
250
function timeFunction(name, fn) {
251
return async (...args) => {
252
const timer = signale.time(name);
253
try {
254
const result = await fn(...args);
255
signale.timeEnd(timer);
256
return result;
257
} catch (error) {
258
signale.timeEnd(timer);
259
signale.error(`Function ${name} failed after timing`);
260
throw error;
261
}
262
};
263
}
264
265
// Usage
266
const timedOperation = timeFunction('data-fetch', async () => {
267
// Simulate async operation
268
await new Promise(resolve => setTimeout(resolve, 1000));
269
return 'data';
270
});
271
272
timedOperation();
273
// Output: ▶ data-fetch Initialized timer...
274
// ◼ data-fetch Timer run for: 1.00s
275
276
// Nested timing
277
async function complexOperation() {
278
signale.time('total');
279
280
signale.time('phase1');
281
await new Promise(resolve => setTimeout(resolve, 500));
282
signale.timeEnd('phase1');
283
284
signale.time('phase2');
285
await new Promise(resolve => setTimeout(resolve, 300));
286
signale.timeEnd('phase2');
287
288
signale.timeEnd('total');
289
}
290
291
complexOperation();
292
// Output: ▶ total Initialized timer...
293
// ▶ phase1 Initialized timer...
294
// ◼ phase1 Timer run for: 500ms
295
// ▶ phase2 Initialized timer...
296
// ◼ phase2 Timer run for: 300ms
297
// ◼ total Timer run for: 800ms
298
```