I want to add a button with one purpose, when the user click, it'll add one more product to the chart.
The thing in my mind is, I'll create a counter, if the user click faster than 0.5 seconds, counter will increase, but the value will not go to the server. When users last click is more than 1 second ago, last value of the counter will go to the server as the order amount. My goal is, if user will add, for example 10 amount of same order very fast, I don't want to send all clicks one by one to the server, instead send all clicks sum (which is the counter value) at once when 1 second passed after last user click.
I saw people says it can be done with NSOperations. But I couldn't figure out how.
var counter = 0
@IBAction func addProductAmount (_ sender: Any) {
// 1. Increase counter
// 2. If only 0.5 seconds or less time passed, don't send the counter value, wait it to be 1 seconds
// 3. Send counter value 1 seconds after last user click
}
Code will be something like this. But how can use Operation Queue for this? Any help? I'm learning swift and I don't know Objective-C at all.
CodePudding user response:
The thing you want to do is called throttling. So you can use this code:
var counter = 0
timer: Timer?
@IBAction func addProductAmount (_ sender: Any) {
counter = 1
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(sendRequest), userInfo: nil, repeats: false)
}
func sendRequest() {
// your method to make a request to the server
}