Method 1: Use the setTimeout ();
function sayHi(){ alert("Hi."); } setTimeout(sayHi, 2000);
Method 2: Use window.requestAnimationFrame to ();
var element = document.getElementById('animate'); element.style.position = 'absolute'; were start = null ; function STEP (timestamp) { IF (! Start) Start = timestamp; var Progress = timestamp - Start; // element continues to the left, the maximum does not exceed 200 pixels element.style.left = Math.min (progress / 10, 200 ) + 'PX' ; // if the distance of the first performance does not exceed 2000 milliseconds, // continue Animate IF (Progress <2000 ) { window.requestAnimationFrame(step); } } window.requestAnimationFrame(step);
Difference between the two:
setTimeout () need to manually set the time delay, and requestAnimationFrame () is executed to be delayed until the next time the browser re-flow. Thus, the former is more generic, which is mainly a function of the discharge methods need to operate the DOM, which will help to enhance the performance;
note:
window.cancelAnimationFrame () which may be used to cancel execution of the callback function.
Method 3: Use window.requestIdleCallback () function will be delayed internal to the system resource is free, when executed;
Usage and window.requestAnimationFrame () is similar, but different postpone conditions also have a method to cancel the execution of:. Window.cancelIdleCallback ()
requestIdleCallback(myNonEssentialWork); function myNonEssentialWork(deadline) { while (deadline.timeRemaining() > 0) { doWorkIfNeeded(); } }