diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index e94069c366..851ae1ef57 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -1384,6 +1384,10 @@ WalSndWaitForWal(XLogRecPtr loc)
 	else
 		RecentFlushPtr = GetXLogReplayRecPtr(NULL);
 
+	/* check whether we're done */
+	if (loc <= RecentFlushPtr)
+		return RecentFlushPtr;
+
 	for (;;)
 	{
 		long		sleeptime;
@@ -1418,6 +1422,10 @@ WalSndWaitForWal(XLogRecPtr loc)
 		else
 			RecentFlushPtr = GetXLogReplayRecPtr(NULL);
 
+		/* check whether we're done */
+		if (loc <= RecentFlushPtr)
+			break;
+
 		/*
 		 * If postmaster asked us to stop, don't wait anymore.
 		 *
@@ -1441,10 +1449,6 @@ WalSndWaitForWal(XLogRecPtr loc)
 			!waiting_for_ping_response)
 			WalSndKeepalive(false);
 
-		/* check whether we're done */
-		if (loc <= RecentFlushPtr)
-			break;
-
 		/* Waiting for new WAL. Since we need to wait, we're now caught up. */
 		WalSndCaughtUp = true;
 
