您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# JavaScript怎么实现间隔和延时
在JavaScript中,实现代码的间隔执行和延时执行是常见的需求。本文将详细介绍`setTimeout`、`setInterval`、`requestAnimationFrame`等核心方法,并提供现代JavaScript(包括ES6+)的最佳实践方案。
## 一、延时执行:setTimeout
### 基本用法
```javascript
setTimeout(() => {
console.log('这段代码将在1秒后执行');
}, 1000);
const timerId = setTimeout(() => {}, 1000);
clearTimeout(timerId); // 取消未执行的延时
setTimeout((name, age) => {
console.log(`姓名:${name},年龄:${age}`);
}, 1000, '张三', 25);
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(`已执行 ${counter} 次`);
if(counter >= 5) clearInterval(intervalId);
}, 1000);
function delayedLoop(count, delay) {
let i = 0;
function execute() {
console.log(`执行第 ${++i} 次`);
if(i < count) setTimeout(execute, delay);
}
setTimeout(execute, delay);
}
function animate() {
// 动画逻辑
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ interval: 1000 });
// worker.js
self.onmessage = function(e) {
setInterval(() => {
self.postMessage('tick');
}, e.data.interval);
};
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
function throttle(fn, interval) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if(now - lastTime >= interval) {
fn.apply(this, args);
lastTime = now;
}
};
}
class PausableTimer {
constructor(callback, interval) {
this.callback = callback;
this.interval = interval;
this.timerId = null;
this.startTime = null;
this.remaining = interval;
}
start() {
this.startTime = Date.now();
this.timerId = setTimeout(() => this.execute(), this.remaining);
}
pause() {
clearTimeout(this.timerId);
this.remaining -= Date.now() - this.startTime;
}
execute() {
this.callback();
this.remaining = this.interval;
this.start();
}
}
// 使用performance.now()获取高精度时间戳
const start = performance.now();
setTimeout(() => {
const end = performance.now();
console.log(`实际延迟:${end - start}ms`);
}, 100);
function batchProcess(items, processItem, batchSize, delay) {
let i = 0;
function processBatch() {
const end = Math.min(i + batchSize, items.length);
for(; i < end; i++) {
processItem(items[i]);
}
if(i < items.length) {
setTimeout(processBatch, delay);
}
}
processBatch();
}
setImmediate(() => {
console.log('在I/O事件回调之后立即执行');
});
process.nextTick(() => {
console.log('在当前操作完成后立即执行');
});
const { setTimeout: nodeSetTimeout } = require('timers/promises');
async function run() {
await nodeSetTimeout(1000);
console.log('1秒后执行');
}
通过合理选择和使用这些定时方法,可以构建出响应迅速、性能优异的JavaScript应用。 “`
这篇文章共计约1300字,涵盖了JavaScript中实现间隔和延时的各种方法及其应用场景,采用Markdown格式编写,包含代码示例和结构化标题。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。