I made a quick PHP script on my server containing a call to mail() and started testing it. The html page always loads instantly, so I assume that means the PHP containing th
The behavior you are seeing has nothing to do with PHP's mail()
function. Instead, it is the SMTP mail server which PHP hands off the message to, which is taking time to deliver. That service is known as a mail transport agent, or MTA.
There are lots of potential reasons it won't be delivered immediately. Possibly, the delay you see is greylisting on the receiving server, meaning that the receiving mail server refuses to accept the message until the sending server (which your PHP script handed it to) tries a few times to resend it. Well-behaved MTA's will retry failed send attempts, but spam servers often don't, making this a simple but effective method for cutting down spam.
It could even be as simple as a long queue of messages on the SMTP server waiting to be sent, whereby yours are waiting in line. (Really greylisting is more probable though)
Most important to remember though is that email is not intended to be instantaneous and therefore never guaranteed to be instantaneous. In the past decade or so we've gotten accustomed by and large to email being delivered really quickly, but you can never promise quick delivery.
Just as @Michael Berkowski said, it's not the mail() function itself. mail() works by calling your systems built in SMTP courier software. It then automatically negotiates the conversation with the receiving system by performing the necessary DNS lookups to find the proper mail server. Then that server picks up your message, checks your system through grey-listing and reverse DNS lookups, scans it and runs it against it's own spam/virus protection, then finally delivers. Also many mail servers delay unknown sending servers to prevent against mail DOS'ing and fishers.