Ever clicked a button twice and accidentally fired off two API calls? Or maybe you started fetching some big data, only to realise you didn’t actually need it anymore. In real life, you’d just hit a Cancel button, right?
Well, JavaScript has a built-in way to do exactly that: AbortController. Think of it like pulling the plug on a task before it finishes.
Example:
Cancelling a fetch request after 2 seconds
const controller = new AbortController();
const signal = controller.signal;
fetch("https://jsonplaceholder.typicode.com/todos/1", { signal })
.then(res => res.json())
.then(data => console.log("Data:", data))
.catch(err => {
if (err.name === "AbortError") {
console.log("❌ Fetch was aborted");
} else {
console.error("Something went wrong:", err);
}
});
// Cancel the request after 2 seconds
setTimeout(() => {
controller.abort();
}, 2000);
Run this, and you’ll see the fetch get cut short. Instead of data, you’ll get an AbortError.
⚙️ How Does It Work?
Think of it like this:
- Controller → The remote control.
- Signal → The wire that connects the remote to the task.
- Task (like fetch) → The TV.
When you call abort(), the signal instantly tells the task: “Stop what you’re doing.”
✍️ Co-authored with: @hrithik_pasumarthi
Top comments (0)