setTimout and setInterval

setTimeout and setInterval allow us to schedule events.

setTimeout

The setTimeout method is a built-in function that allows you to execute a function after a certain amount of time has passed.

First, let’s write a function. This function will create an alert that prints out “5 seconds have passed.” We will then write a setTimeout to run the function after 5 seconds.

function timedAlert() {
  alert("Five seconds have passed.");
}
setTimeout(timedAlert, 5000);

We previously learned that functions need to be invoked in some way, for example user invoked or event invoked. With the setTimeout method, we use setTimeout to invoke our function at a certain time.

The syntax is setTimeout(functionName, milliseconds). So if we want to specify that our function should be invoked after five seconds, we would use 5000, as in the example above.

Whenever the page is reloaded, the alert should pop up after 5 seconds.

Let’s create a second example. First, we will create a random number using our Math.floor(Math.random()) combination. Next, the function winningNumber() prints that number to the webpage, with the text “ is the winning number”. Finally, the function is invoked by the setTimeout method, 2 seconds after the page has loaded.

let rand = Math.floor(Math.random() * 10) + 1;

function winningNumber() {
  document.write(rand + " is the winning number!");
}

setTimeout(winningNumber, 2000);

Examples in codepen:

See the Pen 4.5 Example by LSU DDEM (@lsuddem) on CodePen.

setInterval

If we wanted a function to execute over and over again, we could use the setInterval method. The syntax for that method is similar:

setInterval(functionName, milliseconds) In this case, the milliseconds are the interval between each invocation of the function.

The next example function will create a new date object, then print it as a string in an alert.

The set interval method will run the function every 6 seconds, so the date will update with every new alert. The function will continue to run every six seconds until the end of time (or until the page is closed!)

function dateAlert() {
  let date = new Date();
  alert(date.toString());
}
setInterval(dateAlert, 6000);

Another example:

<div> changing color text </div>
<button onclick="killAlert()"> This Button will Kill the Alert </button>
function changeTextColor() {
  let myDiv = document.querySelector("div");
  if (myDiv.style.color == "black") {
    myDiv.style.color = "pink";
  } else {
    myDiv.style.color = "black";
  }
}

setInterval(changeTextColor, 500);

In this example, the div from the HTML code is stored in a variable, using document.querySelector (which we will learn in the next section!). Then, an if statement checks whether the CSS color is equal to black. If it is, it changes the color to pink. If not, it changes it back to black.

The setInterval invocation means that the color will change every half a second.

Examples in codepen:

See the Pen 4.5 Example_1 by LSU DDEM (@lsuddem) on CodePen.

Clearing setTimeout and setInterval

setTimeout and setInterval can be cleared using clearTimeout and clearInterval.

In order to use these methods in JavaScript, the original method has to be stored in a variable.

This function will print out “Hello again” to the console every 4 seconds. The setInterval to invoke it will be stored in a variable

function greeting() {
  console.log("Hello again");
}

let myGreeting = setInterval(greeting, 4000);

//Now that the setInterval is stored in a variable, clearInterval can be used to stop it, like this:

clearInterval(myGreeting);

Of course, it may not be that useful to immediately clear a setInterval immediately after creating it. A more useful way of using the clearInterval method would be to apply it to a button, so that a setInterval will run until a button is pressed.

Codepen Example:

See the Pen 4.5 Example_2 by LSU DDEM (@lsuddem) on CodePen.

Exercise 4.5

Invoking Functions

  • The code inside of a function will not be executed until the function is told to do so.
  • When we tell a function to run, we are ‘invoking’ the function.
  • Functions can also be invoked by an event. When a specific event occurs, the function is ordered to execute.
  • The event that invokes a function can be anything. Usually, you will see events such as button clicks triggering functions.
    • For example, when a user fills out a form online and clicks the “submit” button, the function that sends the form’s data is invoked and the data is sent to the correct location.
  • Functions can also be invoked by themselves, this is called self invocation.
  • We will visit each of these methods of invocation, beginning with user invocation:
  • To invoke a function we have written, or a function in the JavaScript library, we simply type the function’s name, followed by a pair of parenthesis.
  • If the function requires parameters, we will provide the arguments for these parameters within the parenthesis after the function’s name. Otherwise, we invoke functions without parameters by including the pair of empty parenthesis.

A Simple Adding Function

function adder(value1, value2, value3) {
  return value1 + value2 + value3;
}
  • the function, named adder, takes three parameters.
  • the function returns the sum of all three parameters.
  • the keyword “return” is the indicator of the last line of a function. If any code is placed beyond the return statement, the code will not be executed, as the function exits after executing its return statement.
  • to invoke the function and retrieve the value it returns to us, we can either save the return value to a variable or print the value to the console, like so:
let sumOfNumbers = adder(45, 67, 23);
console.log(sumOfNumbers);

// Orrrr:

console.log(adder(45, 67, 23));
  • Both methods will achieve the same result, but you can see that the second option is more efficient
  • As you can see on line 42, we can pass arguments directly into a function without having to store them as variables first.
  • A Simple Current-Date Printing Function:
function printDate() {
  let today = new Date();
  return today.getMonth() + " / " + today.getDate() + 
    " / " + today.getFullYear();
}
  • the function, named printDate, uses the JavaScript Date object methods getMonth(), getDate(), and getYear() to print the current date in this format: MM / DD / YYYY
  • to use the methods for the JavaScript Date object, we created a new variable named today and declared that it was a date object. You should remember objects from the lesson on data types. Objects can have methods that act like functions, which we will visit in a few lessons, so don’t worry if you are confused about this function.
  • The purpose of this function(for us) is to see an example of a parameter-less function.
  • To invoke the printDate function, we simply save the return value to a variable or print the invocation to the console, like so:
let todaysDate = printDate();
console.log(todaysDate); 

// orrrr:

console.log(printDate()); 
  • Note that we did not pass in arguments in either method because the function does not have parameters.

Exercises

back