Code has been added to clipboard!

Main Tips on Using JavaScript Timers: SetTimeOut vs SetInterval

Reading time 3 min
Published Aug 8, 2017
Updated Oct 2, 2019

JavaScript timing events, or the JavaScript timer feature, defines a function and sets a specific time for its execution. You can also allow a continuous display of functions. Timing events are especially useful when you want to display popups.

This tutorial covers the JavaScript timing events, their types, and usage. You will also learn about the functions used to cancel them. Keep in mind that even though in the examples you'll mostly see JavaScript alert, you can use JavaScript timer events with other features as well.

JavaScript Timer: Main Tips

  • JavaScript allow executing code in specified time intervals. This functionality is called timing events.
  • You can cancel this functionality using clearTimeout() and clearInterval() functions.

Most Common Timer Functions

The variety of functions JavaScript offers is amazing. Using them, you can perform various tasks, thus providing your website with any functionality.

When we wish to execute timing events, we can also choose from a few methods that have different useful functions each. We will now discuss the most commonly used ones and review examples to illustrate each one.

setTimeOut()

This is probably the most common timing event method: it calls a function after a time you have specified passes.

Look at the example below. If you click a button, a JavaScript alert message will pop up after 2 seconds (2000 milliseconds):

Example
<button onclick="setTimeout(showAlert, 2000)">Click me!</button>

clearTimeOut()

This JavaScript timer function cancels the JavaScript setTimeout() function before it is executed.

In the example below, the setTimeout() function again calls a JavaScript alert to pop up after 2 seconds. However, if you call a clearTimeout() function before the seconds pass, it will be canceled:

Example
<button onclick="myVar = setTimeout(showAlert, 2000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>

setInterval()

This JavaScript timer function sets an interval in milliseconds when something should change. In the example below, the displayed time changes every 2 seconds:

Example
var exampleVar = setInterval(exampleTimer, 2000);
function exampleTimer() {
   var d = new Date();
   document.getElementById("example").innerHTML = d.toLocaleTimeString();  
}

clearInterval()

This JavaScript timer function clears the interval, stopping it from running:

Example
var exampleVar = setInterval(exampleTimer, 0);
function exampleTimer() {
    var date = new Date();
    document.getElementById("example").innerHTML = date.toLocaleTimeString();
}

JavaScript Timer: Summary

  • JavaScript timing events means running the code in defined time intervals.
  • You can use JavaScript setTimeOut() function to execute some functionality after a specified amount of time.
  • You can use setInterval() function to execute some functionality continuously with defined breaks inbetween.
  • You can cancel a setTimeOut() by calling clearTimeOut() function.
  • You can cancel a setInterval() by calling JavaScript clearInterval() function.
  • You can combine this functionality with other JavaScript features, like a JavaScript alert popup.
What Is JavaScript Used For?
Tutorial
Introduction
Output
Syntax
Comment
Commands
Operators
Comparison and Logical Operators
Data Types
Math.random()
Type Conversion
Function Definitions
Events
Objects
Object Properties
Prototype
Array
Sorting Arrays
Strings
Numbers
Number Format
Math Object
Onclick Event
Date
Date Formats
Scope
Regular Expressions
Reserved Words
Common Mistakes
Performance
Forms
Form Validation
Window: The Browser Object Model
Popup Boxes
Cookies
JSON
AJAX Introduction
AJAX Form
Automatic File Download
Functions
Array Methods
String Methods
Date Methods
Timing Events
Cheat Sheet
JavaScript in HTML
HTML DOM Methods
HTML DOM Changing HTML
HTML DOM Animation
HTML DOM EventListener
HTML DOM Navigation
HTML DOM NodeList
HTML DOM Element Nodes
Array Functions
Boolean
Calling a Function
Date Functions
Global Objects
Input Text
Operator
Statements
String Functions
Math
Math.random
Number
RegEx
alert
array.filter
array.length
array.map
array.reduce
array.push
array.sort
break and continue
className
confirm
decodeURIComponent
for
forEach
if
indexOf
innerHTML
location.reload
number.toString
onclick
onload
parseInt
prompt
replace
setAttribute
setInterval
setTimeout
slice
splice
string.includes
string.indexOf
string.split
style.display
submit
substr
substring
switch
test
throw, try and catch
toLowerCase
toUpperCase
use strict
while
window.history
window.location
window.navigator
window.screen