Search code examples
iosswiftswiftuitextfieldonchange

How to run code only after a variable hasn't changed after a couple seconds?


I have a TextField that runs a search when the bound variable changes. But I would like for it to wait a second or two before running the search in order to save on resources.

Here's an example:

TextField("Search", text: $searchBody)
    .onChange(of: searchBody) { query in
        print("Search Changed!")
        // Code here runs if searchBody doesn't change after 2 seconds.
    }

Solution

  • The following code should help :)

       TextField("Search", text: $searchBody)
           .onChange(of: searchBody) { query in
               print("Search Changed!")
               // Code here runs if searchBody doesn't change after 2 seconds.
               var tmp = searchBody
               DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                   if tmp == searchBody {
                       //Your code here
                       ...
               }
            
           }
    
       }