Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 使用 Promise 简单封装 setTimeout
- const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
- ;(async () => {
- // 同步
- function debounce(delay, action, init = undefined) {
- let flag
- let result = init
- return function(...args) {
- if (flag) clearTimeout(flag)
- flag = setTimeout(() => {
- const temp = action.apply(this, args)
- if (temp instanceof Promise) {
- temp.then(res => (result = res))
- } else {
- result = temp
- }
- }, delay)
- return result
- }
- }
- const get = async i => i
- console.log(await get(1))
- console.log(await get(2))
- // 注意,修改默认值为 Promise
- const fn = debounce(10, get, 0)
- console.log(fn(3)) // 0
- console.log(fn(4)) // 0
- await wait(20)
- console.log(fn(5)) // 4
- })()
- ;(async () => {
- // 异步
- const debounce = (delay, action, init = undefined) => {
- let flag
- let result = init
- return new Proxy(action, {
- apply(target, thisArg, args) {
- return new Promise(resolve => {
- if (flag) clearTimeout(flag)
- flag = setTimeout(() => {
- result = Reflect.apply(target, thisArg, args)
- resolve(result)
- }, delay)
- setTimeout(() => {
- resolve(result)
- }, delay)
- })
- },
- })
- }
- const get = async i => i
- console.log(await get(1))
- console.log(await get(2))
- // 注意,修改默认值为 Promise
- const fn = debounce(10, get, 0)
- fn(3).then(i => console.log(i)) // 0
- fn(4).then(i => console.log(i)) // 4
- await wait(20)
- fn(5).then(i => console.log(i)) // 5
- })()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement