0
# Timer Control
1
2
Auto-close functionality with comprehensive timer controls and progress indication capabilities for creating time-sensitive popups and notifications.
3
4
## Capabilities
5
6
### Timer State Management
7
8
Methods to check timer status and get remaining time information.
9
10
```typescript { .api }
11
/**
12
* If timer parameter is set, returns number of milliseconds of timer remained
13
* Otherwise, returns undefined
14
* @returns Remaining milliseconds or undefined if no timer is set
15
*/
16
function getTimerLeft(): number | undefined;
17
18
/**
19
* Check if timer is running. Returns true if timer is running,
20
* and false if timer is paused/stopped
21
* If timer parameter isn't set, returns undefined
22
* @returns Timer running status or undefined if no timer is set
23
*/
24
function isTimerRunning(): boolean | undefined;
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
// Monitor timer progress
31
Swal.fire({
32
title: 'Auto-closing notification',
33
text: 'This will close automatically',
34
timer: 5000,
35
timerProgressBar: true,
36
didOpen: () => {
37
const interval = setInterval(() => {
38
const timeLeft = Swal.getTimerLeft();
39
if (timeLeft !== undefined) {
40
console.log(`${Math.ceil(timeLeft / 1000)} seconds remaining`);
41
} else {
42
clearInterval(interval);
43
}
44
}, 100);
45
}
46
});
47
48
// Check timer status
49
if (Swal.isTimerRunning()) {
50
console.log('Timer is currently running');
51
} else {
52
console.log('Timer is paused or not set');
53
}
54
```
55
56
### Timer Control
57
58
Methods to control timer execution during popup display.
59
60
```typescript { .api }
61
/**
62
* Stop timer. Returns number of milliseconds of timer remained
63
* If timer parameter isn't set, returns undefined
64
* @returns Remaining milliseconds or undefined if no timer is set
65
*/
66
function stopTimer(): number | undefined;
67
68
/**
69
* Resume timer. Returns number of milliseconds of timer remained
70
* If timer parameter isn't set, returns undefined
71
* @returns Remaining milliseconds or undefined if no timer is set
72
*/
73
function resumeTimer(): number | undefined;
74
75
/**
76
* Toggle timer. Returns number of milliseconds of timer remained
77
* If timer parameter isn't set, returns undefined
78
* @returns Remaining milliseconds or undefined if no timer is set
79
*/
80
function toggleTimer(): number | undefined;
81
82
/**
83
* Increase timer. Returns number of milliseconds of an updated timer
84
* If timer parameter isn't set, returns undefined
85
* @param ms - The number of milliseconds to add to the current timer
86
* @returns Updated timer milliseconds or undefined if no timer is set
87
*/
88
function increaseTimer(ms: number): number | undefined;
89
```
90
91
**Usage Examples:**
92
93
```typescript
94
// Interactive timer control
95
Swal.fire({
96
title: 'Timer Control Demo',
97
html: `
98
<p>This popup will auto-close in 10 seconds</p>
99
<div style="margin-top: 20px;">
100
<button id="pause-btn" class="swal2-styled">Pause</button>
101
<button id="resume-btn" class="swal2-styled">Resume</button>
102
<button id="add-time-btn" class="swal2-styled">+5s</button>
103
</div>
104
`,
105
timer: 10000,
106
timerProgressBar: true,
107
didOpen: () => {
108
const pauseBtn = document.getElementById('pause-btn');
109
const resumeBtn = document.getElementById('resume-btn');
110
const addTimeBtn = document.getElementById('add-time-btn');
111
112
pauseBtn.addEventListener('click', () => {
113
const remaining = Swal.stopTimer();
114
console.log(`Timer paused with ${remaining}ms remaining`);
115
});
116
117
resumeBtn.addEventListener('click', () => {
118
const remaining = Swal.resumeTimer();
119
console.log(`Timer resumed with ${remaining}ms remaining`);
120
});
121
122
addTimeBtn.addEventListener('click', () => {
123
const newTime = Swal.increaseTimer(5000);
124
console.log(`Timer increased to ${newTime}ms`);
125
});
126
}
127
});
128
129
// Toggle timer on hover
130
Swal.fire({
131
title: 'Hover to pause',
132
text: 'Timer pauses when you hover over this popup',
133
timer: 8000,
134
timerProgressBar: true,
135
didOpen: (popup) => {
136
popup.addEventListener('mouseenter', () => {
137
Swal.stopTimer();
138
});
139
140
popup.addEventListener('mouseleave', () => {
141
Swal.resumeTimer();
142
});
143
}
144
});
145
```
146
147
## Timer Configuration
148
149
Timer-related options in `SweetAlertOptions`:
150
151
```typescript { .api }
152
interface TimerOptions {
153
/**
154
* Auto close timer of the popup. Set in ms (milliseconds)
155
* @default undefined
156
*/
157
timer?: number;
158
159
/**
160
* If set to true, the timer will have a progress bar at the bottom of a popup
161
* Mostly, this feature is useful with toasts
162
* @default false
163
*/
164
timerProgressBar?: boolean;
165
}
166
```
167
168
## Common Timer Patterns
169
170
### Toast Notifications
171
172
```typescript
173
// Success toast with timer
174
const Toast = Swal.mixin({
175
toast: true,
176
position: 'top-end',
177
showConfirmButton: false,
178
timer: 3000,
179
timerProgressBar: true,
180
didOpen: (toast) => {
181
toast.addEventListener('mouseenter', Swal.stopTimer);
182
toast.addEventListener('mouseleave', Swal.resumeTimer);
183
}
184
});
185
186
Toast.fire({
187
icon: 'success',
188
title: 'Signed in successfully'
189
});
190
191
// Error toast with longer timer
192
Toast.fire({
193
icon: 'error',
194
title: 'Login failed',
195
timer: 5000
196
});
197
```
198
199
### Auto-closing Confirmations
200
201
```typescript
202
// Confirmation with countdown
203
let timeLeft = 10;
204
const countdownInterval = setInterval(() => {
205
timeLeft--;
206
Swal.update({
207
html: `This action will be confirmed automatically in ${timeLeft} seconds`,
208
timer: undefined // Reset timer to prevent conflict
209
});
210
211
if (timeLeft <= 0) {
212
clearInterval(countdownInterval);
213
Swal.clickConfirm();
214
}
215
}, 1000);
216
217
const result = await Swal.fire({
218
title: 'Auto-confirm',
219
html: `This action will be confirmed automatically in ${timeLeft} seconds`,
220
showCancelButton: true,
221
confirmButtonText: 'Confirm Now',
222
cancelButtonText: 'Cancel',
223
allowOutsideClick: false,
224
willClose: () => {
225
clearInterval(countdownInterval);
226
}
227
});
228
```
229
230
### Progress Indication
231
232
```typescript
233
// File upload with timer-based progress
234
const uploadProgress = (duration: number) => {
235
return new Promise((resolve) => {
236
let progress = 0;
237
const totalSteps = 100;
238
const stepDuration = duration / totalSteps;
239
240
Swal.fire({
241
title: 'Uploading...',
242
html: 'Progress: 0%',
243
timer: duration,
244
timerProgressBar: true,
245
allowOutsideClick: false,
246
didOpen: () => {
247
const interval = setInterval(() => {
248
progress++;
249
Swal.update({
250
html: `Progress: ${progress}%`
251
});
252
253
if (progress >= totalSteps) {
254
clearInterval(interval);
255
Swal.update({
256
title: 'Upload Complete!',
257
html: 'Your file has been uploaded successfully',
258
icon: 'success',
259
timer: 2000
260
});
261
setTimeout(resolve, 2000);
262
}
263
}, stepDuration);
264
}
265
});
266
});
267
};
268
269
// Usage
270
await uploadProgress(5000); // 5 second upload simulation
271
```
272
273
### Dynamic Timer Adjustment
274
275
```typescript
276
// Adaptive timer based on content length
277
const showAdaptiveNotification = (message: string) => {
278
// Calculate reading time: ~200 words per minute, ~5 characters per word
279
const readingTime = Math.max(3000, (message.length / 5) * 60 / 200 * 1000);
280
281
Swal.fire({
282
title: 'Notification',
283
text: message,
284
timer: readingTime,
285
timerProgressBar: true,
286
showConfirmButton: false,
287
didOpen: () => {
288
console.log(`Auto-closing in ${readingTime}ms based on content length`);
289
}
290
});
291
};
292
293
// Short message (3 second minimum)
294
showAdaptiveNotification('Saved!');
295
296
// Long message (calculated based on length)
297
showAdaptiveNotification('Your changes have been saved successfully. The system has automatically created a backup of your previous version and updated all related references. You can continue working with confidence knowing your data is secure.');
298
```
299
300
### Conditional Timer Control
301
302
```typescript
303
// Timer that stops on validation errors
304
Swal.fire({
305
title: 'Quick Form',
306
html: '<input id="quick-input" class="swal2-input" placeholder="Enter something">',
307
timer: 10000,
308
timerProgressBar: true,
309
showConfirmButton: true,
310
confirmButtonText: 'Submit',
311
didOpen: () => {
312
const input = document.getElementById('quick-input');
313
314
input.addEventListener('input', (e) => {
315
const value = e.target.value;
316
317
if (value.length > 0) {
318
// Stop timer when user starts typing
319
Swal.stopTimer();
320
} else {
321
// Resume timer if input is cleared
322
Swal.resumeTimer();
323
}
324
});
325
},
326
preConfirm: () => {
327
const input = document.getElementById('quick-input');
328
const value = input.value;
329
330
if (!value) {
331
Swal.showValidationMessage('Please enter something');
332
// Add extra time for user to correct
333
Swal.increaseTimer(5000);
334
return false;
335
}
336
337
return value;
338
}
339
});
340
```
341
342
### Multi-stage Timer Process
343
344
```typescript
345
// Multi-step process with different timer durations
346
const runMultiStageProcess = async () => {
347
// Stage 1: Preparation (3 seconds)
348
await Swal.fire({
349
title: 'Preparing...',
350
text: 'Setting up the process',
351
timer: 3000,
352
timerProgressBar: true,
353
showConfirmButton: false,
354
allowOutsideClick: false
355
});
356
357
// Stage 2: Processing (8 seconds with dynamic updates)
358
let stage2Complete = false;
359
const stage2Promise = new Promise<void>((resolve) => {
360
let progress = 0;
361
Swal.fire({
362
title: 'Processing...',
363
html: 'Step 1 of 4',
364
timer: 8000,
365
timerProgressBar: true,
366
showConfirmButton: false,
367
allowOutsideClick: false,
368
didOpen: () => {
369
const interval = setInterval(() => {
370
progress++;
371
const step = Math.ceil(progress / 20);
372
Swal.update({
373
html: `Step ${step} of 4`
374
});
375
376
if (progress >= 80) {
377
clearInterval(interval);
378
stage2Complete = true;
379
resolve();
380
}
381
}, 100);
382
}
383
});
384
});
385
386
await stage2Promise;
387
388
// Stage 3: Completion (2 seconds)
389
await Swal.fire({
390
title: 'Complete!',
391
text: 'Process finished successfully',
392
icon: 'success',
393
timer: 2000,
394
timerProgressBar: true,
395
showConfirmButton: false
396
});
397
};
398
399
// Execute the multi-stage process
400
runMultiStageProcess();
401
```
402
403
## Timer Integration with Events
404
405
```typescript
406
// Advanced timer integration with lifecycle events
407
Swal.fire({
408
title: 'Event-driven Timer',
409
text: 'Watch the console for timer events',
410
timer: 8000,
411
timerProgressBar: true,
412
showCancelButton: true,
413
willOpen: () => {
414
console.log('Timer will start when popup opens');
415
},
416
didOpen: () => {
417
console.log('Timer started');
418
419
// Log timer status every second
420
const logInterval = setInterval(() => {
421
const timeLeft = Swal.getTimerLeft();
422
const isRunning = Swal.isTimerRunning();
423
console.log(`Timer: ${timeLeft}ms left, running: ${isRunning}`);
424
425
if (timeLeft === undefined) {
426
clearInterval(logInterval);
427
}
428
}, 1000);
429
},
430
willClose: () => {
431
console.log('Timer stopped - popup closing');
432
},
433
didClose: () => {
434
console.log('Timer completed or popup was closed');
435
}
436
});
437
```