Function to know when to stop iterating