javascript setTimeout(function(){}),setTimeout(()=>{})

该文展示了JavaScript中使用setTimeout的两种方式,分别是传统的函数表达式和现代的箭头函数表达式,并在页面上通过myFunction更新内容的例子。

两种不同的书写风格。

1.setTimeout(function(){})

2.setTimeout(()=>{})

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>
<h2>setInterval() with a Callback</h2>

<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>

<h1 id="demo"></h1>

<script>
setTimeout(function(){ myFunction("I love You !!!"); }, 3000);
setTimeout(()=>{myFunction("I'm Michael")},3000);

function myFunction(value) {
  document.getElementById("demo").innerHTML += value;
}
</script>

</body>
</html>

代码在线演示。https://bamboobook.w3spaces-preview.com/setTimeout.html

你提供的 `throttle`(节流)函数实现基本思路是正确的,但存在几个 **逻辑问题** 和 **代码结构问题**,会导致功能不完全符合预期。下面我们来逐步分析并优化它。 --- ### 🔍 你的代码存在的问题 ```javascript const throttle = (func, delay = 50, immediate = false) => { let isThrottle = false return function(...args) { if(!isThrottle) { if(immediate) { func.apply(this, args) isThrottle =true setTimeout(() => { isThrottle = false }, delay); } else { setTimeout(() => { func.apply(this, args) isThrottle =true setTimeout(() => { isThrottle = false }, delay) }, delay) } } } } ``` #### ❌ 问题 1:嵌套的 `setTimeout` 逻辑混乱 - 在 `immediate: true` 的情况下,执行了 `func` 后设置 `isThrottle = true`,然后使用一个 `setTimeout` 将其设为 `false`。 - 但在 `immediate: false` 的情况下,你在 `setTimeout` 中才执行 `func`,这导致 `isThrottle` 被设置为 `true` 并立即又被设为 `false`,逻辑错误。 - 嵌套两个 `setTimeout` 是多余的,而且容易出错。 #### ❌ 问题 2:在 `setTimeout` 中调用 `func.apply(this, args)` 时,`this` 可能丢失 - 如果返回的是箭头函数(如你当前写法),那么 `this` 会绑定到外层作用域,而不是调用者对象。 - 更推荐使用普通函数来确保 `this` 正确绑定。 --- ### ✅ 改进后的版本(修复逻辑 + 明确 this) ```javascript function throttle(func, delay = 50, immediate = false) { let isThrottled = false; let timer = null; return function(...args) { const context = this; if (!isThrottled) { if (immediate) { func.apply(context, args); isThrottled = true; timer = setTimeout(() => { isThrottled = false; }, delay); } else { timer = setTimeout(() => { func.apply(context, args); isThrottled = true; setTimeout(() => { isThrottled = false; }, delay); }, delay); } } }; } ``` > ⚠️ 注意:即使我们在这里使用了普通函数,仍然需要通过 `context = this` 来捕获正确的上下文,因为 `setTimeout` 内部的 `this` 会指向全局对象(如 `window` 或 `undefined`)。 --- ### ✅ 使用示例 ```javascript const log = throttle((x) => { console.log('Called with:', x); }, 200, true); log(1); // 立即执行 log(2); // 被节流 log(3); // 被节流 ``` --- ### ✅ 总结 - 你的节流函数的结构是正确的,但逻辑上存在嵌套和顺序的问题。 - 推荐使用普通函数返回,以确保 `this` 绑定正确。 - 不建议在 `setTimeout` 中直接使用 `this`,应提前保存 `this` 到变量中。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值