-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool-68-JavaScript-Memory-Leak-Simulator.html
More file actions
520 lines (449 loc) · 18.2 KB
/
tool-68-JavaScript-Memory-Leak-Simulator.html
File metadata and controls
520 lines (449 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tool 68 - JavaScript Memory Leak Simulator - Developer Toolbox</title>
<link rel="stylesheet" href="assets/core.css">
<style>
.split-view {
display: grid;
grid-template-columns: 1fr;
gap: 1.5rem;
margin-bottom: 2rem;
margin-top: 1rem;
}
@media (min-width: 900px) {
.split-view {
grid-template-columns: 350px 1fr;
}
}
.controls-panel {
background: rgba(0, 0, 0, 0.4);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 1rem;
}
select.pattern-selector,
textarea.code-area {
width: 100%;
background: var(--bg-main);
color: #7ee787;
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
padding: 0.8rem;
font-family: var(--font-mono);
font-size: 0.85rem;
outline: none;
}
textarea.code-area {
height: 180px;
resize: vertical;
}
button.action-btn {
background: rgba(255, 255, 255, 0.1);
color: var(--text-main);
border: 1px solid var(--border-color);
padding: 0.8rem;
font-weight: bold;
border-radius: var(--radius-sm);
cursor: pointer;
transition: all 0.2s;
}
button.action-btn:hover {
background: rgba(255, 255, 255, 0.2);
}
button.action-btn.danger {
background: rgba(255, 85, 85, 0.2);
color: #ff5555;
border-color: #ff5555;
}
button.action-btn.danger:hover {
background: rgba(255, 85, 85, 0.4);
}
/* Chart Canvas */
.chart-container {
background: rgba(0, 0, 0, 0.3);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
padding: 1rem;
height: 250px;
position: relative;
}
#memoryChart {
width: 100%;
height: 100%;
display: block;
}
.stats-overlay {
position: absolute;
top: 1rem;
right: 2rem;
background: rgba(0, 0, 0, 0.8);
padding: 0.5rem 1rem;
border-radius: 4px;
font-family: var(--font-mono);
font-size: 0.85rem;
color: #7ee787;
border: 1px solid var(--border-color);
}
/* 3D Canvas wrapper */
.graph-container {
background: #000;
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
height: 350px;
position: relative;
overflow: hidden;
box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.8);
margin-top: 1rem;
}
#sandbox-frame {
width: 0;
height: 0;
border: 0;
position: absolute;
left: -9999px;
}
</style>
</head>
<body class="theme-dark">
<main class="main-content" style="padding-top:2rem;">
<div class="container" style="max-width: 1200px;">
<div class="tool-header">
<div>
<a href="index.html" class="back-link">← Back to Toolbox</a>
<h1>68. JavaScript Memory Leak Simulator</h1>
</div>
<div>
<select id="theme-select" aria-label="Select Theme">
<option value="dark">Dark Theme</option>
<option value="light">Light Theme</option>
<option value="solarized">Solarized</option>
<option value="neon">Neon Glow</option>
<option value="highcontrast">High Contrast</option>
</select>
</div>
</div>
<div class="glass-panel">
<div class="split-view">
<!-- Controls -->
<div class="controls-panel">
<label style="color:var(--text-secondary); font-size:0.85rem; font-weight:bold;">Leak Pattern
Simulator</label>
<select id="pattern-select" class="pattern-selector">
<option value="array">Growing Array (Closure Reference)</option>
<option value="dom">Detached DOM Elements</option>
<option value="events">Unbound Event Listeners</option>
</select>
<textarea id="code-snippet" class="code-area" readonly></textarea>
<div style="display:flex; gap:0.5rem; margin-top:0.5rem;">
<button id="btn-start" class="action-btn danger" style="flex:1;">Start Leaking!</button>
<button id="btn-stop" class="action-btn" style="flex:1;">Stop</button>
</div>
<button id="btn-fix" class="action-btn" style="color:#56b6c2; border-color:#56b6c2;">Apply Fix &
Garbage Collect</button>
<div
style="font-size:0.8rem; color:var(--text-secondary); text-align:justify; margin-top:1rem; line-height:1.4;">
*This simulator executes real JavaScript causing memory growth in a sandboxed iframe. Modern
browsers obscure exact JS heap limits, so we track approximate JS Heap Size using
<code>performance.memory</code>.
</div>
</div>
<!-- Right panel -->
<div>
<!-- Chart -->
<div class="chart-container">
<canvas id="memoryChart"></canvas>
<div class="stats-overlay">
JS Heap: <span id="lbl-heap">0 MB</span>
</div>
</div>
<!-- 3D Visualization -->
<div class="graph-container" id="graph-container">
<!-- 3D Pipe goes here -->
</div>
</div>
</div>
</div>
</div>
</main>
<iframe id="sandbox-frame"></iframe>
<footer class="global-footer">
<div class="container">
Made with ❤️ by <a href="https://github.com/Aliriyaj007" target="_blank">Aliriyaj007</a>
</div>
</footer>
<script src="assets/core.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
<script>
const patternSelect = document.getElementById('pattern-select');
const codeSnippet = document.getElementById('code-snippet');
const btnStart = document.getElementById('btn-start');
const btnStop = document.getElementById('btn-stop');
const btnFix = document.getElementById('btn-fix');
const lblHeap = document.getElementById('lbl-heap');
const ctx = document.getElementById('memoryChart').getContext('2d');
const sandbox = document.getElementById('sandbox-frame');
const patterns = {
array: {
bad: `let theThing = null;
let replaceThing = function () {
let originalThing = theThing;
let unused = function () { if (originalThing) console.log("hi"); };
theThing = {
longStr: new Array(1000000).join('*'),
someMethod: function () { console.log("message"); }
};
};
// Called every 100ms`,
fixed: `let theThing = null;
let replaceThing = function () {
let originalThing = theThing;
let unused = function () { if (originalThing) console.log("hi"); };
theThing = {
longStr: new Array(10000).join('*'), // Much shorter, or avoid entirely
someMethod: function () { console.log("message"); }
};
};`
},
dom: {
bad: `let detachedNodes = [];
function createNodes() {
for(let i=0; i<1000; i++) {
let div = document.createElement("div");
document.body.appendChild(div);
detachedNodes.push(div);
document.body.removeChild(div);
}
}
// Called every 100ms`,
fixed: `let detachedNodes = [];
function createNodes() {
// Stop holding references to removed nodes
detachedNodes = [];
}`
},
events: {
bad: `let listeners = [];
function bindEvent() {
let hugeObject = new Array(100000).fill('leak');
let handler = function() { console.log(hugeObject.length); };
window.addEventListener('resize', handler);
listeners.push(handler);
}
// Called every 100ms`,
fixed: `let listeners = [];
function bindEvent() {
// Remove previous listeners to prevent build-up
listeners.forEach(fn => window.removeEventListener('resize', fn));
listeners = [];
}`
}
};
function updateCode() {
codeSnippet.value = patterns[patternSelect.value].bad;
}
patternSelect.addEventListener('change', updateCode);
updateCode();
let isRunning = false;
let leakTimer = null;
let pMemory = window.performance && window.performance.memory ? window.performance.memory : null;
let chartData = Array(50).fill(0);
function formatMB(bytes) {
return (bytes / 1024 / 1024).toFixed(1) + ' MB';
}
function drawChart() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const w = ctx.canvas.width;
const h = ctx.canvas.height;
const maxVal = Math.max(...chartData, 100);
ctx.beginPath();
ctx.moveTo(0, h);
chartData.forEach((val, i) => {
const x = (i / (chartData.length - 1)) * w;
const y = h - ((val / maxVal) * h * 0.9);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.strokeStyle = '#ff5555';
ctx.lineWidth = 2;
ctx.stroke();
// Gradient fill
ctx.lineTo(w, h);
ctx.lineTo(0, h);
const grad = ctx.createLinearGradient(0, 0, 0, h);
grad.addColorStop(0, 'rgba(255,85,85,0.4)');
grad.addColorStop(1, 'rgba(255,85,85,0)');
ctx.fillStyle = grad;
ctx.fill();
}
function resizeChart() {
const container = document.querySelector('.chart-container');
ctx.canvas.width = container.clientWidth - 2;
ctx.canvas.height = container.clientHeight - 2;
drawChart();
}
window.addEventListener('resize', resizeChart);
setTimeout(resizeChart, 100);
function updateMemoryStats() {
if (pMemory) {
// performance.memory is non-standard but works in Chrome
const used = pMemory.usedJSHeapSize;
lblHeap.textContent = formatMB(used);
chartData.shift();
chartData.push(used / 1024 / 1024);
} else {
// Mock leak for browsers without performance.memory
const last = chartData[chartData.length - 1];
let next = isRunning ? last + Math.random() * 5 : last - Math.random();
if (next < 10) next = 10;
chartData.shift();
chartData.push(next);
lblHeap.textContent = next.toFixed(1) + ' MB (sim)';
}
drawChart();
}
setInterval(updateMemoryStats, 500);
// Simulator Logic
function execSandbox(code) {
const win = sandbox.contentWindow;
try {
win.eval(code);
} catch (e) { console.error(e); }
}
btnStart.addEventListener('click', () => {
isRunning = true;
btnStart.style.opacity = '0.5';
const pat = patternSelect.value;
// Inject leak setup based on pattern
execSandbox(patterns[pat].bad);
if (leakTimer) clearInterval(leakTimer);
leakTimer = setInterval(() => {
if (pat === 'array') execSandbox('replaceThing&&replaceThing();');
if (pat === 'dom') execSandbox('createNodes&&createNodes();');
if (pat === 'events') execSandbox('bindEvent&&bindEvent();');
}, 100);
leakIntensity = 1.0; // 3D effect
});
btnStop.addEventListener('click', () => {
isRunning = false;
btnStart.style.opacity = '1';
clearInterval(leakTimer);
leakIntensity = 0; // 3D effect
});
btnFix.addEventListener('click', () => {
isRunning = false;
btnStart.style.opacity = '1';
clearInterval(leakTimer);
codeSnippet.value = patterns[patternSelect.value].fixed;
// Reload iframe to clear memory fully
sandbox.src = "about:blank";
setTimeout(() => {
execSandbox(patterns[patternSelect.value].fixed);
if (patternSelect.value === 'array') execSandbox('replaceThing&&replaceThing();');
}, 100);
// Mock GC for chart drop if needed
if (!pMemory) {
chartData = chartData.map(v => v * 0.2);
}
leakIntensity = 0;
animateDropClear();
});
// 3D Visualization of a "Leaking Pipe"
let scene, camera, renderer;
let drops = [];
let pipe;
let leakIntensity = 0; // 0 to 1
function init3D() {
const container = document.getElementById('graph-container');
const cw = container.clientWidth;
const ch = container.clientHeight;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(60, cw / ch, 1, 100);
camera.position.set(0, 5, 20);
camera.lookAt(0, 0, 0);
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(cw, ch);
container.appendChild(renderer.domElement);
const light = new THREE.DirectionalLight(0xffffff, 1.2);
light.position.set(10, 20, 10);
scene.add(light);
scene.add(new THREE.AmbientLight(0x404040));
// Pipe
const pipeGeo = new THREE.CylinderGeometry(2, 2, 20, 32);
pipeGeo.rotateZ(Math.PI / 2);
const pipeMat = new THREE.MeshPhongMaterial({ color: 0x555555, shininess: 100 });
pipe = new THREE.Mesh(pipeGeo, pipeMat);
pipe.position.y = 5;
scene.add(pipe);
// Hole in pipe
const holeGeo = new THREE.CircleGeometry(0.8, 16);
holeGeo.rotateX(Math.PI / 2);
const holeMat = new THREE.MeshBasicMaterial({ color: 0x000000 });
const hole = new THREE.Mesh(holeGeo, holeMat);
hole.position.set(0, 3.01, 0);
scene.add(hole);
// Pool at bottom
const poolGeo = new THREE.PlaneGeometry(30, 30);
poolGeo.rotateX(-Math.PI / 2);
const poolMat = new THREE.MeshPhongMaterial({ color: 0xff5555, transparent: true, opacity: 0.8, shininess: 90 });
const pool = new THREE.Mesh(poolGeo, poolMat);
pool.position.y = -8;
scene.add(pool);
window.addEventListener('resize', () => {
if (!container) return;
const rw = container.clientWidth;
const rh = container.clientHeight;
camera.aspect = rw / rh;
camera.updateProjectionMatrix();
renderer.setSize(rw, rh);
});
animate3D();
}
const dropGeo = new THREE.SphereGeometry(0.3, 16, 16);
const dropMat = new THREE.MeshPhongMaterial({ color: 0xff5555, shininess: 100 });
function createDrop() {
const drop = new THREE.Mesh(dropGeo, dropMat);
drop.position.set((Math.random() - 0.5) * 1.5, 3, (Math.random() - 0.5) * 1.5);
drop.userData = { vy: -0.1 };
scene.add(drop);
drops.push(drop);
}
function animateDropClear() {
// Shrink all drops rapidly to simulate GC
drops.forEach(d => { d.userData.gc = true; });
}
function animate3D() {
requestAnimationFrame(animate3D);
if (leakIntensity > 0) {
if (Math.random() < 0.2 * leakIntensity) {
createDrop();
}
}
for (let i = drops.length - 1; i >= 0; i--) {
const d = drops[i];
if (d.userData.gc) {
d.scale.multiplyScalar(0.8);
if (d.scale.x < 0.01) {
scene.remove(d);
drops.splice(i, 1);
}
} else {
d.userData.vy -= 0.01; // gravity
d.position.y += d.userData.vy;
if (d.position.y < -8) {
// hit pool
d.userData.gc = true;
}
}
}
renderer.render(scene, camera);
}
document.addEventListener('DOMContentLoaded', init3D);
</script>
</body>
</html>