我想添加一個具有一個目的的按鈕,當用戶單擊時,它會在圖表中再添加一個產品。
我的想法是,我會創建一個計數器,如果用戶點擊速度超過 0.5 秒,計數器會增加,但值不會發送到服務器。當用戶最后一次點擊超過 1 秒前,計數器的最后一個值將作為訂單金額發送到服務器。我的目標是,如果用戶會非常快速地添加,例如 10 筆相同的訂單,我不想將所有點擊一一發送到服務器,而是一次發送所有點擊總和(即計數器值)最后一次用戶點擊后 1 秒過去了。
我看到人們說它可以用 NSOperations 來完成。但我不知道怎么做。
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
}
代碼將是這樣的。但是如何使用操作佇列呢?有什么幫助嗎?我學得很快,但我根本不知道 Objective-C。
uj5u.com熱心網友回復:
你想做的事情叫做throttling。所以你可以使用這個代碼:
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/515418.html
標籤:IOS迅速
