Advertisement
Guest User

Untitled

a guest
May 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. // 使用 Promise 简单封装 setTimeout
  2. const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
  3.  
  4. ;(async () => {
  5. // 同步
  6. function debounce(delay, action, init = undefined) {
  7. let flag
  8. let result = init
  9. return function(...args) {
  10. if (flag) clearTimeout(flag)
  11. flag = setTimeout(() => {
  12. const temp = action.apply(this, args)
  13. if (temp instanceof Promise) {
  14. temp.then(res => (result = res))
  15. } else {
  16. result = temp
  17. }
  18. }, delay)
  19. return result
  20. }
  21. }
  22.  
  23. const get = async i => i
  24.  
  25. console.log(await get(1))
  26. console.log(await get(2))
  27. // 注意,修改默认值为 Promise
  28. const fn = debounce(10, get, 0)
  29. console.log(fn(3)) // 0
  30. console.log(fn(4)) // 0
  31. await wait(20)
  32. console.log(fn(5)) // 4
  33. })()
  34. ;(async () => {
  35. // 异步
  36. const debounce = (delay, action, init = undefined) => {
  37. let flag
  38. let result = init
  39. return new Proxy(action, {
  40. apply(target, thisArg, args) {
  41. return new Promise(resolve => {
  42. if (flag) clearTimeout(flag)
  43. flag = setTimeout(() => {
  44. result = Reflect.apply(target, thisArg, args)
  45. resolve(result)
  46. }, delay)
  47. setTimeout(() => {
  48. resolve(result)
  49. }, delay)
  50. })
  51. },
  52. })
  53. }
  54.  
  55. const get = async i => i
  56.  
  57. console.log(await get(1))
  58. console.log(await get(2))
  59. // 注意,修改默认值为 Promise
  60. const fn = debounce(10, get, 0)
  61. fn(3).then(i => console.log(i)) // 0
  62. fn(4).then(i => console.log(i)) // 4
  63. await wait(20)
  64. fn(5).then(i => console.log(i)) // 5
  65. })()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement