# Timing Functions

Many built in javascript functions take callback functions. For example, `setInterval` and `setTimeout` both take a function and run it at a specific time.

## setTimeout & setInterval

`setTimeout` takes two arguments:

* the function to be run
* how long to wait (in milliseconds) before running that function

```javascript
function alarm() {
    console.log("Wake up!");
}

setTimeout(alarm, 10000);
```

`setInterval` also takes two arguments:

* the function to be run
* how often to run the function (in milliseconds)

```javascript
function annoy() {
  console.log('Are we there yet?');
}

setInterval(annoy, 1000);
```

You may want to have multiple instances of these timing events going, so you can differentiate between the instances by assigning the functions to variables.

```javascript
function alarm() {
    console.log("Wake up!");
}

const firstAlarm = setTimeout(alarm, 3000);
const secondAlarm = setTimeout(alarm, 6000);
```

```javascript
function annoy() {
    console.log('Are we there yet?');
}

function shutDown() {
    console.log('No!');
}

const kids = setInterval(annoy, 1000);
const parents = setInterval(shutDown, 3200);
```

You can disable an interval using `clearInterval`:

```javascript
function annoy() {
    console.log('Are we there yet?');
}
function hush() {
    clearInterval(kids);
}
const kids = setInterval(annoy, 1000);
setTimeout(hush, 10000);
```

And you can disable your `setTimeout` before the function fires using `clearTimeout`:

```javascript
function alarmRing() {
    console.log('RRRIIINNNGGGGG');
}

function turnOffSnooze() {
    console.log("turning snooze off now");
    clearTimeout(snoozeAlarm);
}

const snoozeAlarm = setTimeout(alarmRing, 3000);

const snoozeOff = setTimeout(turnOffSnooze, 10000);
```

### Exercises:

***1.*** Use `setInteral` and `setTimeout` to write a program that prints the following:

(This should mimic a countdown, so each line will print after a one second delay.)

```bash
10
9
8
7
6
5
4
3
2
1
Blast off!
```

***2.*** How could you mimic the `setInterval` functionality using `setTimeout`? Use `setTimeout` to recreate the `var kids = setInterval(annoy, 1000);` functionality.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://romebell.gitbook.io/seirfx-621/javascript/01functions/03timing-functions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
