Lesson 4 of 10
Cooldowns
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
The canUse, use and remaining functions
Explanation
Every ability in a game has a cooldown. A fireball, for example, goes off and then has to wait three seconds before it can go off again. You don't need a countdown that runs every frame: store when the ability will be ready with readyAt[name] = now + duration, and compare the time against it when someone asks. Nothing has to update every frame, and there's no timer that someone might forget to stop.
The function doesn't read the clock itself. The time is passed in as the now parameter: in FiveM it comes from GetGameTimer(), in LÖVE from love.timer.getTime(), and in a check it's any number you choose. That way the same functions work on the server clock, in a paused game, and in a check that gives the same result every time.
A common mistake is to check only in the UI. A grayed-out button doesn't stop a player with a modded copy of the game from sending the event to the server a hundred times a second, so use does its own check. And when it rejects a request, it leaves the timer alone. Otherwise a player who pressed a moment too early would be punished with a whole new cooldown.
Your task
Complete the canUse(name, now), use(name, now) and remaining(name, now) functions in Cooldowns. An ability that hasn't been used yet is ready, and once it's used it becomes ready when now reaches the time it was used plus its duration from durations. use returns true and starts the cooldown, or returns false without changing anything. remaining returns the time left, and what it returns is never less than zero.
Checks
6 checks- An ability that hasn't been used is ready
- The use function starts the cooldown
- The ability becomes ready exactly when the duration is up
- A use during the cooldown is refused and doesn't extend it
- The remaining function counts down and never goes below zero
- Each ability has its own timer