g
Printer Friendly Version

editor  
BellaOnline's JavaScript / Java Editor
 

Hearing Dog Tool - Adding Randomness

In previous articles, 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, waits for a set amount of time and then 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 add an element of randomness, setting the alarm to a random time between 30 and 120 seconds.

I started by writing a function to pick a random number between two numbers given as arguments.

function get_random( $max, $min)
{
// return a random number between $min and $max
$diff=$max-$min
return (Math.floor((Math.random() % 1) * $diff) + $min);
}

Most of the work here is done by functions from the JavaScript math library, which we use to pick a number between zero and the difference between our two numbers. Then we add the minimum number to this value so that the result is between our two numbers. (If you aren't familiar with random numbers, you might want to check out this article.)

Then I simply called this function with appropriate arguments (120 and 30) in my do_alarm function where I had previously just defined a number to use as seconds to wait.


function do_alarm(){
// mark alarm as set
document.getElementById("alarm_button").disabled=true
document.getElementById("alarm_button").value="Alarm Set"
// determine time to wait in seconds
wait_secs=get_random(120, 30)
// wait for time to be up & sound alarm
setTimeout("sound_alarm()", (wait_secs * 1000))
}

Now the program alarm is set to a random interval, although it otherwise works exactly the same as my last revision. You can view all the code and try out a working example here.

This site needs an editor - click to learn more!

JavaScript / Java Site @ BellaOnline
View This Article in Regular Layout

Content copyright © 2013 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 Editor Wanted for details.



| About BellaOnline | Privacy Policy | Advertising | Become an Editor |
Website copyright © 2013 Minerva WebWorks LLC. All rights reserved.


BellaOnline Editor