JavaScript Wait: Adding Dynamic Timing Events To Your Webpage

stopwatchAdding JavaScript to your site is a great way to turn those dull, static pages into lively and interactive ones.

Part of your website’s new found dynamism may require certain JavaScript functions to pause, or wait, before executing the next code block. Developers may find themselves searching for a JavaScript wait() function, or something similar. Perhaps the closest you’ll get is JavaScript’s set of timing events, including the setTimeout() function, which we’ll learn more about in this guide.

This guide assumes a basic understanding of JavaScript. Have some catching up to do? Try out this JavaScript For Beginners course.

The setTimeout() Function

The setTimeout() function in JavaScript can be used to trigger a code block after a designated number of milliseconds. The syntax for the function is as follows:

setTimeout(function,milliseconds);

Here, you would substitute function with your desired JavaScript function, and milliseconds with the amount of milliseconds you want the code to wait until it executes that particular function.

setTimeout() Example

Let’s say you wanted a message to appear after the user click a button on your web page, after two seconds have passed.

You have your HTML document…

<!DOCTYPE html>
<html>
<body>

...

</body>
</html>

… but what next?

Step 1 – Create the button

<button onclick="exampleFunction()">Click Here!</button>

Our button reads “Click Here!” Upon clicking this button, the function titled exampleFunction() will execute.

Step 2 – Write the setTimeout() function

Between <script> tags, we write out our function using the syntax indicated before. In this example, we’ll create an alert box with the message, “You did it!” after two seconds, or 2000 milliseconds.

<script>
function exampleFunction()
{
setTimeout(function(){alert(“You did it!”)},2000);
}
</script>

Step 3 – Add it all together!

For clarification, we’ve added an explanation of the button’s mechanics in the <p> tag.

<!DOCTYPE html>
<html>
<body>

<p>Click the button. After two seconds, a prompt will appear.</p>
<button onclick="exampleFunction()">Click Here!</button>

<script>
function exampleFunction()
{
setTimeout(function(){alert("You did it!")},2000);
}
</script>

</body>
</html>

Our webpage, complete with button and delayed prompt box, should look like this:

setTimeout

(Code edited and tested via the code editor on W3Schools.com.)

For extra help, check out JavaScript: The Beginner’s Guide.

Erase the setTimeout() Function

If circumstance calls for it, you can create a way for the user to cancel the setTimeout() function before it executes its designated code block. This is done with the clearTimeout() function. The only condition is the clearTimeout() function must be triggered before the setTimeout() function’s millisecond timeframe is up. Otherwise, it will not effectively cancel the function out.

In order to use the clearTimeout() function, you need to use a global variable for the setTimeout() function.

myTimer = setTimeout(function,milliseconds);

Let’s see the clearTimeout() function in action!

<!DOCTYPE html>
<html>
<body>

<p>Click the button. After two seconds, a prompt will appear.</p>
<p>Click the second button before the two seconds is up, and the prompt will not appear.</p>
<button onclick="exampleFunction()">Click Here!</button>
<button onclick="stopFunction()">Prevent the Prompt!</button>

<script>
var myTimer;

function exampleFunction()
{
myTimer=setTimeout(function(){alert("You did it!")},2000);
}

function stopFunction()
{
clearTimeout(myTimer);
}
</script>

</body>
</html>

What we’ve done is create two buttons, one that triggers exampleFunction, and the other that triggers stopFunction. Clicking the exampleFunction button triggers our setTimeout() function, which creates a pop-up prompt after two seconds which reads, “You did it!” This function is associated with the global variable myTimer.

Clicking the stopFunction button triggers the clearTimeout() function, which ends the function associated with the myTimer variable. If the user clicks the first button, and then clicks the second one before the two seconds is over, the prompt will not appear.

Feeling lost? Check out this entry-level JavaScript course for more help!

The setInterval() Function

You can use the setInterval() function, another one of JavaScript’s timing methods, to repeatedly execute a code block, once at every designated interval. This will continue endlessly, until the function is cleared.

The syntax for the setInterval() function is the same as it is for the setTimeout() function:

setInterval(function,milliseconds);

Just as before, the first parameter needs to be a function. The second parameter will still be a time value in milliseconds, but it will be used to designate how often the function should occur. Example: every 2000 milliseconds, every 5000 milliseconds, etc.

Example

<p>Clicking the button will trigger a prompt after two seconds.</p>
<p>After exiting the prompt, another one will appear after two seconds, again.</p>
<button onclick="exampleInterval()">Click Here!</button>

<script>
function exampleInterval()
{
setInterval(function(){alert("You did it... again!")},2000);
}
</script>

Timer Example Using setInterval()

The example above is a little bland, and not likely something you’ll be using unless you really want to annoy your site’s viewers! For something a little more practical, let’s create a timer using the setInterval() function.

<!DOCTYPE html>
<html>
<body>

<p>What time is it?</p>
<p id="demo"></p>

<script>
var myTimer=setInterval(function(){exampleTimer()},1000);
</script>

</body>
</html>

First, we create the setInterval() function to trigger the exampleTimer() function every second, or 1000 milliseconds. This means that every second, our function titled exampleTimer() will display. This will occur continually, without the need for the user to manually trigger it.

But what is exampleTimer()?

function exampleTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}

exampleTimer fetches the current time and displays it in text. This will create the illusion of ticking seconds on a timer, when technically the timer is just displaying the new, current time every second… one second at a time!

Result

<!DOCTYPE html>
<html>
<body>

<p>What time is it?</p>
<p id="demo"></p>

<script>
var myTimer=setInterval(function(){exampleTimer()},1000);

function exampleTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
</script>

</body>
</html>

Test Time!

If you want some practice with your newfound knowledge, use the clearInterval() method to stop the current displayed time, creating a stopwatch effect. The solution will be displayed below.


<!DOCTYPE html>
<html>
<body>

<p>Stop the clock!</p>
<p id="demo"></p>
<button onclick="stopFunction()">Stop</button>

<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function stopFunction()
{
clearInterval(myVar);
}
</script>

</body>
</html>

Clever uses of the JavaScript wait and stop functions, like the one above, can be used to add all sorts of cool, interactive elements to your webpage. Learn more about JavaScript with this Introduction to JavaScript course. Already know the basics? Move on over to Advanced JavaScript Programming and start studying!