search-forward will throw an error by default if the string is not found. This will throw control out of your function which isn't catching errors. To use search-forward in a loop it is best to set the NOERROR argument to t: