Cancel a timed event in Swift?

前端 未结 7 1962
说谎
说谎 2020-11-27 15:36

I want to run a block of code in 10 seconds from an event, but I want to be able to cancel it so that if something happens before those 10 seconds, the code won\'t run after

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 16:10

    For some reason, NSObject.cancelPreviousPerformRequests(withTarget: self) was not working for me. A work around I thought of was coming up with the max amount of loops I'd allow and then using that Int to control if the function even got called.

    I then am able to set the currentLoop value from anywhere else in my code and it stops the loop.

    //loopMax = 200
    var currentLoop = 0
    
    func loop() {      
      if currentLoop == 200 {      
         //do nothing.
      } else {
         //perform loop.
    
         //keep track of current loop count.
         self.currentLoop = self.currentLoop + 1
    
         let deadline = DispatchTime.now() + .seconds(1)
         DispatchQueue.main.asyncAfter(deadline: deadline) {
    
         //enter custom loop parameters
         print("i looped")
    
         self.loop()
       }
    
    }
    

    and then elsewhere in your code you can then

    func stopLooping() {
    
        currentLoop = 199
        //setting it to 199 allows for one last loop to happen. You can adjust based on the amount of loops you want to be able to do before it just stops. For instance you can set currentLoop to 195 and then implement a fade animation while loop is still happening a bit.
    }
    

    It's really quite dynamic actually. For instance you can see if currentLoop == 123456789, and it will run infinitely (pretty much) until you set it to that value somewhere else in your code. Or you can set it to a String() or Bool() even, if your needs are not time based like mine were.

提交回复
热议问题