Hearing Dog Training Tool – setTimeout()

Hearing Dog Training Tool – setTimeout()
In a previous article, I started the iterative development of a small JavaScript program to assist in training a dog to do sound alerts. So far, the program, which you can view here, includes a set alarm button which, when pressed, pops up an alert stating that the alarm has gone off (although the audible alarm is not yet configured.) As the next step, we are going to actually set the wait between pressing the "set alarm" button and the alarm, such as it is, going off.

JavaScript and the Document Object Model (DOM), have a bunch of event handlers to wait for something to happen (i.e. onClick, onMouseOver, ...); however in this case, we want to wait for an amount of time to pass, the DOM provides a method to do this as well setTimeout(). setTimeout() requires two arguments, a piece of code or a function to run and the time to wait in milliseconds before running it. set_timeout() can also take an optional third option designating the scripting language used - JavaScript, JScript, or VBScript (this is part of the DOM, not JavaScript, remember.)

Our new code looks like the following:

function do_alarm(){
// determine time to wait in seconds
wait_secs=52; // for now, just define it
// wait for time to be up & sound alarm
setTimeout(sound_alarm(), (wait_secs * 1000))

This works great, but it is hard to tell, because nothing changes after you press the button until the time is up. However, the DOM can help us with this as well. I added the following 2 lines to the beginning of the do_alarm() function:

// mark alarm as set
document.getElementById("alarm_button").value="Alarm Set"

This changes the button we pushed to set the alarm to say "Alarm Set" and disables it. If we want to be able to use the alarm again, we'll have to change the button back to it's original state. I added this to the sound_alarm() function. You can view all the code and try out a working example here.

This site needs an editor - click to learn more!

You Should Also Read:
Program Planning – Hearing Dog Alert Training Tool
Iterative Development First Pass – Hearing Dog Training Tool
JavaScript Resources

Related Articles
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map

Content copyright © 2023 by Julie L Baumler. All rights reserved.
This content was written by Julie L Baumler. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.