Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Measuring the elapsed time

This Ruby code measures how long it takes to display the message "hello world".
def test_method(statement)
  start_time = Time.now
  eval(statement)
  end_time = Time.now
  end_time - start_time
end

statement = "sleep 1.5; puts 'hello world'"
elapsed_time = test_method(statement)
puts "elapsed time : #{elapsed_time}"

output
hello world
elapsed time : 1.499266

Capturing the value from an HTML text box - Ajax style

This extract of JavaScript code illustrates how the value of a text box on an HTML form could be saved efficiently when used with AJAX.
<input type="text" name="proj1" id="proj1" value="Car_log" 
  onkeyup="timed_updateSummaryCRecord(event.keyCode, '1','project', this.value)" />

The onkeyup event retrieves the user input as soon as the key is pressed, then the event.keyCode is validated to ensure only alpha-numeric characters trigger the save routine.
function timed_updateSummaryCRecord(keyCode, parent_id, field,  val) {
  if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
    clearTimeout(t);
    t = setTimeout("updateSummaryCRecord('" + parent_id + "', '" + field + "', '" + val + "')", 1000);
  }
}

The setTimeout will trigger the save routine after 1 second, however if the user continues to type before the 1 second timer has elapsed, the running timer will be cancelled and the new timer will start.

Note: keyCode value '8' is accepted because it is the backspace key. It would also be helpful to accept the delete key press.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS