async function fetchHTML(url) { // 添加一个超时时间,10秒 const timeout = 10000; const controller = new AbortController(); const id = setTimeout(() => controller.abort(), timeout);

try { const response = await fetch(url, { signal: controller.signal }); const data = await response.text(); clearTimeout(id); return data; } catch (err) { clearTimeout(id); throw err; } }

// 使用示例 fetchHTML('https://www.example.com') .then(data => console.log(data)) .catch(err => console.error(err));

JavaScript fetch() 函数添加超时机制

原文地址: https://www.cveoy.top/t/topic/lPe2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录