JavaScript setTimeout()
We continue in the Speedy Chef project folder throughout this section.
Comparing setTimeout to setInterval
The setInterval
method we just looked at repeatedly calls a function, or runs some code, with a time delay between. Another timing method we have available is setTimeout
. This method will run a function or some code once after a time delay.
Using setTimeout
And we can use this to run the endOfGame
function once the time is up.
It looks similar to the setInterval
method we just used, let’s add this at the bottom of the script:
// index.js
setTimeout();
It also takes in two things, first is the code we want to run. In our case, we want to run the endOfGame
function:
setTimeout(endOfGame, );
Followed by a time delay in milliseconds:
setTimeout(endOfGame, 2000);
This is the delay before the code or function will run. To test this works, add a console.log
to the endOfGame
function:
function endOfGame() {
console.log('ended');
gameStarted = false;
document.querySelector('#endBtn').style.display = 'none';
document.querySelector('#startBtn').style.display = 'inline';
}
Try this out and you should see a log after two seconds.
Using setTimeout
But we want this to run at the end of the game, so instead we can set the time delay to be the same as the length of the game. And we have this game length already stored in the gameLength
variable:
For testing, drop this down to three seconds:
const gameLength = 3;
And set as our time delay:
// convert to milliseconds:
setTimeout(endOfGame, gameLength * 1000);
- Test- console log should show after three seconds
- Remove console log from the endOfGame function
- Reinstate game time to be 300 seconds.
To stop our timeout running when the game is not running, we can wrap this in a function:
function gameTimer() {
setTimeout(endOfGame, gameLength * 1000);
}
And call this function when the game starts:
function startOfGame() {
// ...
gameTimer();
}
Inside the startOfGame
function, we can also use setTimeout
with a message to the user. Add this at the end of the function:
function startOfGame() {
// ...
// 1. set message
document.querySelector('#message').innerText =
'Chef, our first orders are coming in!!!';
// 2. clear message after 3 seconds
setTimeout(function() {
document.querySelector('#message').innerText = '';
}, 3000);
}
This message should run when the game begins and be removed after three seconds. This is JavaScript timers, and you can see how useful they can be. We also have some more timers to add soon, but next we will cover clearing timers when they are no longer needed.