Back to Blog

When meetings don't have a timeout... #coding #programming #shorts

Sandy LaneSandy Lane

Video: When meetings don't have a timeout... #coding #programming #shorts by Taught by Celeste AI - AI Coding Coach

Watch full page →

When Meetings Don't Have a Timeout: The Importance of Timeouts in Async Programming

Just like meetings that drag on without a set end time, asynchronous operations without timeouts can run indefinitely, causing delays and blocking important tasks. Setting timeouts ensures your async code fails fast and recovers gracefully when something takes too long.

Code

async function fetchDataWithTimeout(url, timeoutMs) {
  return new Promise((resolve, reject) => {
    // Create a timeout to reject the promise after timeoutMs milliseconds
    const timeoutId = setTimeout(() => {
      reject(new Error('Operation timed out'));
    }, timeoutMs);

    fetch(url)
      .then(response => {
        clearTimeout(timeoutId); // Clear timeout if fetch completes in time
        resolve(response);
      })
      .catch(err => {
        clearTimeout(timeoutId);
        reject(err);
      });
  });
}

// Example usage:
fetchDataWithTimeout('https://api.example.com/data', 5000)
  .then(response => console.log('Data received:', response))
  .catch(error => console.error('Failed:', error.message));

Key Points

  • Async operations without timeouts can hang indefinitely, blocking progress.
  • Implementing timeouts helps your program fail fast and handle delays gracefully.
  • Use a timer to reject a promise if the async task exceeds the allowed time.
  • Always clear the timeout if the operation completes successfully to avoid memory leaks.