|
47 | 47 | * What about getDerivedStateFromProps and getSnapshotBeforeUpdate methods?
|
48 | 48 | * How to achieve exact behavior like componentDidUpdate in functional components?
|
49 | 49 | * What is debouncing and throttling? Differences between them.
|
| 50 | + |
| 51 | +## What is a debounce function? |
| 52 | + |
| 53 | +Debounce function limits the execution of a function call and waits for a certain amount of time before running it again. |
| 54 | + |
| 55 | +```js |
| 56 | +const debounceFunc = (func, delay) => { |
| 57 | + let timer; |
| 58 | + return function(...args) { |
| 59 | + const context = this; |
| 60 | + clearTimeOut(timer); |
| 61 | + timer = setTimeOut(() => { |
| 62 | + func.apply(context, args); |
| 63 | + }, delay) |
| 64 | + }} |
| 65 | +``` |
| 66 | + |
| 67 | + |
| 68 | +## What is throttle function? |
| 69 | + |
| 70 | +Throttling is a technique, to limit the execution of an event handler function, even when this event triggers continuously due to user actions. (ex: browser resizing) |
| 71 | + |
| 72 | +```js |
| 73 | +const throttleFunc = (func, interval) => { |
| 74 | + let shouldFire = true; |
| 75 | + return function() { |
| 76 | + if (shouldFire) { |
| 77 | + func(); |
| 78 | + shouldFire = false; |
| 79 | + setTimeOut(() => { |
| 80 | + shouldFire = true; |
| 81 | + }, interval) |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | +``` |
| 86 | + |
| 87 | + |
| 88 | + |
50 | 89 | * Code debouncing.
|
0 commit comments