怎样推迟某个函数的执行
方法1: 使用setTimeout(); function sayHi(){ alert("Hi."); } setTimeout(sayHi, 2000); 方法2: 使用window.requestAnimationFrame(); var element = document.getElementById('animate'); element.style.position = 'absolute'; var start = null; function step(timestamp) { if (!start) start = timestamp; var progress = timestamp - start; // 元素不断向左移,最大不超过200像素 element.style.left = Math.min(progress / 10, 200) + 'px'; // 如果距离第一次执行不超过 2000 毫秒, // 就继续执行动画 if (progress < 2000) { window.requestAnimationFrame(step); } } window.requestAnimationFrame(step); 两者区别: setTimeout()需要手动设置延迟时间, 而requestAnimationFrame(