ข้ามไปเนื้อหาหลัก

Performance API — วัด timing ใน browser อย่างแม่นยำ

performance.now() คืน timestamp millisecond ที่แม่นยำกว่า Date.now() เพราะวัดจาก navigation start ไม่ใช่ Unix epoch

const start = performance.now();
// ... code ที่ต้องการวัด
const end = performance.now();
console.log(`ใช้เวลา ${(end - start).toFixed(2)}ms`);

User Timing API — mark และ measure แบบ named:

performance.mark('fetch-start');
await fetchData();
performance.mark('fetch-end');

performance.measure('fetch-duration', 'fetch-start', 'fetch-end');

const [entry] = performance.getEntriesByName('fetch-duration');
console.log(entry.duration);  // ms

ดูทั้งหมด:

performance.getEntriesByType('measure');   // user measures
performance.getEntriesByType('resource');  // network requests
performance.getEntriesByType('navigation'); // page load timing

ใน DevTools แท็บ Performance จะแสดง user marks เป็น markers บน timeline — ช่วย debug ได้ดีมาก