Coroutine timer running crazy fast

Hi,
I am trying to do a simple timer that counts down from 300 through a coroutine. The problem is, it’s over in the snap of a finger. There’s no way it’s 300 seconds, more like 3. Any idea why? Here’s the code.

public float timeRemaining = 300f;

void Start () {
    StartCoroutine(Countdown());
}
	
IEnumerator Countdown()
    {
        while (true)
        {
            for (float timer = 0; timer < 300; timer += Time.deltaTime)
            {
                timeRemaining -= timer;
                yield return 0;
            }
        }

    }

That for loop is confusing, and probably not what you want.

You’re subtracting timer from your time remaining, but the value of timer increases during each frame. A conventional timer reduces the counter by each frame’s deltaTime; your timer reduces the counter by the sum of all deltaTimes.

Try something closer to this:

void Start() {
    StartCoroutine(Countdown(300f)); //maybe use a smaller delay for testing
}

IEnumerator Countdown(float secondsLeft) {
    while (secondsLeft > 0f) {
        secondsLeft -= Time.deltaTime;
        yield return null;
    }
    
    Debug.Log("Countdown finished!");
}

I spot a problem with ‘timeRemaining’. You should be subtracting Time.deltaTime from timeRemaining, not ‘timer’. Timer will continue to grow, so you will be subtracting ever increasing amounts from timeRemaining for each frame.

timeRemaining -= Time.deltaTime;

BTW: It seems a bit convoluted to structure things this way. Why not just base your for() loop on timeRemaining, bailing out when it is <= 0.0.