DEBOUNCE AND THROTTLE.
- Limiting the frequency of events, particularly those initiated by users such as clicks, scrolls or keypresses is best managed through debouncing and throttling techniques in computer programming. These methods aim to control the number of times that an event handler function executes. Though their end goal may be similar, they do so using distinct procedures.
- Debouncing refers to a technique where a function is only executed after a certain amount of time has passed since the last time it was triggered. For example, imagine a user typing a search query into a search box. Every time the user types a character, an event is triggered that executes a function to update the search results. However, if the user types quickly, the function might execute multiple times before the user finishes typing, leading to unnecessary requests to the server. By debouncing the event, the function will only execute after a certain amount of time has passed since the last keypress, giving the user time to finish typing and reducing the number of requests to the server.
- Throttling, on the other hand, refers to a technique where a function is executed at a maximum rate, regardless of how many times it is triggered. For example, imagine a user scrolling a webpage. Every time the user scrolls, an event is triggered that executes a function to update the display. However, if the user scrolls quickly, the function might execute multiple times per second, leading to performance issues. By throttling the event, the function will only execute at a maximum rate, such as once per second, regardless of how many times it is triggered.
- In summary, debounce and throttle are two techniques used to manage the frequency of events in computer programming. Debouncing delays the execution of a function until a certain amount of time has passed since the last event, while throttling limits the rate at which a function can be executed, regardless of how many events are triggered.
- Here are examples of how debounce and throttle can be implemented in iOS Swift:
1. Debounce:
In this example, we’ll assume you have a search bar (searchBar
) and you want to delay sending a network request until the user has stopped typing for a certain amount of time. To debounce the search bar input, you can use the Timer
class to delay the execution of the search request until the user stops typing.
class SearchViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
var searchTimer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
}
func search(text: String) {
// send network request and update search results
}
}
extension SearchViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchTimer?.invalidate()
searchTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] _ in
self?.search(text: searchText)
}
}
}
In this example, the search
function sends a network request and updates the search results. The searchBar
delegate is set to the view controller, which allows us to implement the searchBar(_:textDidChange:)
function. In this function, we first invalidate the current searchTimer
(if it exists), and then create a new Timer
with a delay of 0.5 seconds. When the timer fires, it executes the search
function with the current search text.
2. Throttle:
In this example, we’ll assume you have a scroll view (scrollView
) and you want to limit the frequency of updates to the scroll position to avoid performance issues. To throttle the scroll view updates, you can use the CADisplayLink
class to update the scroll position at a maximum rate.
class ScrollViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
var lastUpdateTime: CFTimeInterval = 0
let minUpdateTimeInterval: CFTimeInterval = 0.1
lazy var displayLink: CADisplayLink = {
let displayLink = CADisplayLink(target: self, selector: #selector(updateScrollPosition))
displayLink.add(to: .current, forMode: .common)
return displayLink
}()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
}
@objc func updateScrollPosition() {
let currentTime = CACurrentMediaTime()
if currentTime - lastUpdateTime >= minUpdateTimeInterval {
// update scroll position
lastUpdateTime = currentTime
}
}
}
extension ScrollViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// start display link if it's not already running
if !displayLink.isPaused { return }
displayLink.isPaused = false
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// stop display link when scrolling ends
if !decelerate {
displayLink.isPaused = true
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// stop display link when scrolling ends
displayLink.isPaused = true
}
}
In this example, the updateScrollPosition
function updates the scroll position of the scrollView
. The displayLink
is a CADisplayLink
that fires at a rate of 60 frames per second (i.e., every 16.7ms). In the scrollViewDidScroll
delegate method, we start the display
Thanks for your reading!