简体   繁体   中英

How can I lock an async function so it waits for the first call to finish before running again

I dont want the same async function running multiple times in a row. I want the function to wait until the first call of the function to finish before having the ability to run again

I've tried unwiring the event and then wiring it back up but that doesn't seem to stop the function from being called multiple times

code:

 func scrollViewDidScroll(scrollView: UIScrollView)
{
 myScrollView.delegate = nil
 myAsync()
 myScrollView.delegate = self
}

I've also tried setting the delegates to nil and self inside of the function but that didn't work either

You could introduce a Bool property running and set it to true when the async function is called. When the async function finishes set it back to false . Then you only call the async function when running == false

func scrollViewDidScroll(scrollView: UIScrollView) {
    if !running {
        running = true
        myAsync()
    }
}

func myAsync() {
    // do your async stuff
    running = false // this has to be done on the main thread after the async stuff has finished
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM