不止热门角色,我们为你扩展了更多细分角色分类,覆盖职场提升、商业增长、内容创作、学习规划等多元场景。精准匹配不同目标,让每一次生成都更有方向、更高命中率。
立即探索更多角色分类,找到属于你的增长加速器。
延迟 3 秒后切换轮播图可见项(使用 setTimeout,含错误处理与取消支持)
'use strict';
/**
* 切换指定容器内的 .slide 项,仅显示目标索引项。
* @param {{ selector: string, index: number }} params
* - selector: 容器选择器(例如 '#banner'),容器下应包含若干 .slide 元素
* - index: 目标要显示的 .slide 索引(从 0 开始)
*/
function switchSlide({ selector, index }) {
// 参数校验
if (typeof selector !== 'string' || !selector.trim()) {
console.warn('[switchSlide] Invalid selector:', selector);
return;
}
const root = document.querySelector(selector);
if (!root) {
console.warn(`[switchSlide] Element not found for selector: "${selector}"`);
return;
}
const items = root.querySelectorAll('.slide');
const count = items.length;
if (count === 0) {
console.warn(`[switchSlide] No ".slide" elements inside "${selector}"`);
return;
}
// 索引合法性校验
const safeIndex = Number(index);
if (!Number.isInteger(safeIndex)) {
console.warn(`[switchSlide] Index must be an integer. Received: ${index}`);
return;
}
if (safeIndex < 0 || safeIndex >= count) {
console.warn(`[switchSlide] Index out of bounds (${safeIndex}). Valid range: 0 - ${count - 1}`);
return;
}
// 切换显示状态
items.forEach((el, i) => {
el.style.display = i === safeIndex ? 'block' : 'none';
});
}
/**
* 使用 setTimeout 在指定延迟后执行 switchSlide。
* @param {number} delayMs - 延迟毫秒数,必须为非负有限数
* @param {{ selector: string, index: number }} params - 传给回调的参数
* @returns {number} timeoutId - 定时器 ID,可用于 clearTimeout 取消
*/
function scheduleSwitch(delayMs, params) {
if (!Number.isFinite(delayMs) || delayMs < 0) {
throw new Error(`delayMs must be a non-negative finite number. Received: ${delayMs}`);
}
// 安全执行:捕获回调中的异常,避免未处理错误中断后续逻辑
const timeoutId = setTimeout(() => {
try {
switchSlide(params);
} catch (err) {
console.error('[scheduleSwitch] Unexpected error while switching slide:', err);
}
}, delayMs);
return timeoutId;
}
// 要求:延迟时间 3000ms,执行功能为显示 #banner 容器内第 2 个 .slide(索引 1)
const timeoutId = scheduleSwitch(3000, { selector: '#banner', index: 1 });
// 如需在延迟期间取消执行(例如用户交互变化):
/* clearTimeout(timeoutId); */
延迟 5 秒后显示 Toast,并在 2 秒后自动移除的安全版 setTimeout 实现
/**
* 在指定延迟后显示一条 toast 消息,并在 2 秒后自动移除。
* 返回一个对象,可用于取消尚未触发的延迟执行。
*
* 设计原则:
* - 使用 textContent 避免 XSS 风险,替代不安全的 innerHTML。
* - 参数与类型校验,避免运行时错误。
* - 提供取消功能,避免页面切换或组件卸载时的内存泄漏。
*
* @param {Object} options
* @param {number} options.delay 延迟时间,毫秒。必须为非负有限数值。
* @param {string} options.message 要显示的提示消息。
* @param {string} options.container 容器的选择器(如 "#notify")。
* @returns {{ id: number|null, cancel: function }} 返回超时定时器 id 和取消函数。
*/
function showTimeoutToast({ delay = 5000, message, container }) {
// 基本校验
if (typeof delay !== 'number' || !Number.isFinite(delay) || delay < 0) {
throw new TypeError('delay 必须为非负有限数值');
}
if (typeof container !== 'string' || container.trim() === '') {
throw new TypeError('container 必须为非空字符串选择器');
}
// 环境校验(SSR/非浏览器场景)
if (typeof document === 'undefined') {
console.warn('当前环境不存在 document,跳过 UI 显示');
return { id: null, cancel: () => {} };
}
// 外层延迟:在 delay 毫秒后显示 toast
const timeoutId = setTimeout(() => {
try {
const c = document.querySelector(container);
if (!c) {
console.warn(`未找到容器: ${container}`);
return;
}
// 使用安全的 DOM API 构建内容,避免使用 innerHTML
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = String(message ?? '');
// 将 toast 插入容器
c.appendChild(toast);
// 内层延迟:2 秒后移除 toast
const removeId = setTimeout(() => {
// 确保 toast 仍在对应容器中再移除
if (toast && toast.parentNode === c) {
c.removeChild(toast);
}
// 移除局部引用,帮助 GC
}, 2000);
// 可选:将 removeId 记录在元素上(便于调试或高级控制)
toast.dataset.removeTimeoutId = String(removeId);
} catch (err) {
console.error('显示 toast 过程中发生错误:', err);
}
}, delay);
// 提供取消尚未执行的外层定时器的能力
return {
id: timeoutId,
cancel: () => {
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
}
};
}
说明:
<!-- 示例容器 -->
<div id="notify"></div>
<!-- 可选:简单的样式,让 toast 更明显 -->
<style>
.toast {
display: inline-block;
padding: 8px 12px;
background: #333;
color: #fff;
border-radius: 4px;
font-size: 14px;
box-shadow: 0 4px 10px rgba(0,0,0,0.2);
}
</style>
<script>
// 将上面的 showTimeoutToast 函数粘贴到此处或在外部脚本中引入
// 调用:5 秒后显示提示,并在 2 秒后自动移除
const timer = showTimeoutToast({
delay: 5000,
message: '请求超时,请稍后再试',
container: '#notify'
});
// 如果需要取消尚未触发的显示(例如用户已成功返回数据)
// 可在合适的时机调用:
// timer.cancel();
</script>
用一句话说明“延迟多久、要做什么”,即可生成一份可直接使用的 JavaScript 定时器代码与清晰的使用指南;默认补全命名、注释、异常与边界处理,帮助你快速完成动画延迟、交互提醒、轮播切换、加载超时、防抖等高频需求;通过引导式追问澄清需求细节,避免遗漏;让新人快速上手、资深开发更高效,减少返工与沟通成本,统一团队代码风格,稳定交付质量,提升上线成功率。