Hi,
I want to set a function that will count how long a button is held down for however when the button is released I need to run another function that will pass the length of time and a variable passed by the button on to a script usin AJAX. Now im fine with the AJAX once I have my variables but its the bit about setting the variable to the length of time the button was down

Im guessing it will be something like this:

//When button is pressed
function button_down('direction') {
//The variable for counting the time
var Time
//Code for counting
}

//Button up
function button_up() {
//Ajax that sends the variable direction and Time to a script
//Dont bother writing this bit I am OK with it
}

Thanx,
Sam Rudge

Javascript uses a function called setTimeout that's used to call a function after a specific number of seconds. Knowing this, you can set up the scenario like this:

var time_held = 0; //these are defined outside
var being_held = false; //the functions
var time_out = 1000;

function button_down('direction'){
  being_held = true;
  time = 0;
  setTimeout(increment_count, time_out); //1000 milliseconds == 1 second.
}

function increment_count(){
  if (being_held == false){return;}
  time += time_out; //amount of milliseconds elapsed
  setTimeout(increment_count, time_out); //keep going until button is released
}

function button_up(){
  being_held = false; //remove this and the sky will fall on your head.
  if (time > 0){ time /= 1000; } //if you use a time_out less than 1000 milliseconds (now, don't change the 1000 in "time /= 1000; that's for translating the milliseconds into seconds), you'll get more precision on this number. You'll need to format it to how many decimal places you want.
  //do what you want from here on in.
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.