We know from fermat's principle that light follows the smallest path. But how light know that which path is smallest?
A way to understand this, is to imagine that light actually follows all paths. However, most paths experience destructive interference with other paths. The only paths that do not experience destructive interference are those in the neighbourhood of paths with stationary (e.g., minimal) action (time).
I strongly recommend reading Feynman's QED: The Strange Theory of Light and Matter. In the link you'll also find a link to video.