javascript tiemout and intervals


a set time period has elapsed   [ɪˈlæpst]  (时间)消逝,流逝 elapse的过去分词和过去式

setTimeout()
Execute a specified block of code once after a specified time has elapsed.
等一个指定的时间再次执行。
 |....------|.--------|

setInterval()
Execute a specified block of code repeatedly with a fixed time delay between each call.
间隔固定的时间重复执行。
 |....------|.------|

requestAnnimationFrame()
The modern version of setInterval(),Executes a specified block of code before the browser next repaints the display, allowing an animation to be run at a suitable framerate regardless of the environment it is being run in.

The asynchronous code  set up by these functions runs on the main thread (after their specified timer has elapsed).

before a setTimeout() call executes, 
两个参数:一个函数,一个number单位是毫秒。 setTimeout(fn, 0)
这个时间是最小间隔时间,间隔时间可能会超过这个时间, 主线程上运行完了后,才会执行,所有这个间隔时间= 主线程现有的任务运行时间+间隔时间。


let myGreeting = setTimeout(() => {
  alert('Hello, Mr. Universe!');
}, 2000);

// With a named function
let myGreeting = setTimeout(function sayHi() {
  alert('Hello, Mr. Universe!');
}, 2000);

// With a function defined separately
function sayHi() {
  alert('Hello Mr. Universe!');
}

let myGreeting = setTimeout(sayHi, 2000);


clearTimeout(myGreeting);

setTimeout() returns an identifier value that can be used to refer to the timeout later, such as when you want to stop it.
See Clearing timeouts (below) to learn how to do that.

an identifier value   : myGreeting

Passing parameters to a setTimeout() function.


function sayHi(who) {
  alert(`Hello ${who}!`);
}

let myGreeting = setTimeout(sayHi, 2000, 'Mr. Universe');




阅读量: 581
发布于:
修改于: