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

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

TimeLine //JavaScript Class




Simulates the Adobe Flash timeline. You define the amount of frames, the speed in fps (frames per second) and, at each frame passage an event is called, useful for animations.

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/timeline [v1.0]

TimeLine = function(fps, f){
	this.fps = fps, this.frames = f;
};
with({o: TimeLine, $: TimeLine.prototype}){
	o.timers = [];
	$.running = !!($.current = +(o.timer = $.time = null));
	o.run = function(){
		var o = this;
		o.timer || (o.timer = setInterval(function(){
			for(var h, d = +(new Date), t = o.timers, i = t.length; i--;){
				(!t[i].running || ((d - t[i].time) / (1e3 / t[i].fps) > t[i].current + 1 &&
				t[i].onframe(++t[i].current), t[i].current >= t[i].frames)) &&
				(h = t.splice(i, 1)[0], h.stop(1));
			}
		}, 1));
	};
	$.start = function(c){
		var o = this, t = TimeLine;
		if(o.running) return;
		o.running = true, o.current = c || 0;
		o.time = new Date, o.onstart && o.onstart();
		if(!o.onframe || o.frames <= 0 || o.fps <= 0)
			return o.stop(1);
		t.timers.push(this), t.run();
	};
	$.stop = function(){
		var o = this;
		o.running = false;
		if(!TimeLine.timers.length)
			TimeLine.timer = clearInterval(TimeLine.timer), null;
		arguments.length && o.onstop && o.onstop();
	};
}


Example


<div id="box" style="position: absolute; top: 100px; background: #efe; width: 100px; height: 100px">25 fps</div>
<div id="box2" style="position: absolute; top: 300px; background: #ff9; width: 100px; height: 100px">12 fps</div>

<strong>TimeLine working together with the ease in quad function.</strong><br />

<script type="text/javascript">
Math.ease = function (t, b, c, d) {
	if ((t /= d / 2) < 1)
		return c / 2 * t * t + b;
	return -c / 2 * (--t * (t - 2) - 1) + b;
};

var o = new TimeLine(25, 50), d = document, b = d.getElementById("box");
o.onframe = function(){
	b.style.left = Math.ease(this.current, 0, 400, 30) + "px";
};
o.onstart = function(){
	d.body.appendChild(d.createTextNode("Started"));
};
o.onstop = function(){
	d.body.appendChild(d.createTextNode(" - Finished (" + (((new Date) - this.time)) + " msec)"))
	d.body.appendChild(d.createElement("br"));
	this.start();
};
o.start();


var o2 = new TimeLine(12, 50), b2 = d.getElementById("box2");
o2.onframe = function(){
	b2.style.left = Math.ease(this.current, 0, 400, 30) + "px";
};
o2.onstop = function(){
	this.start();
};
o2.start();
</script>

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.

Code execution timer

These two bits of code can be used to record & output the execution time of a piece of code in microseconds. NOTE: The functions used here are only available on BSD-like systems (I think).
/* Put this line at the top of the file: */
#include <sys/time.h>

/* Put this right before the code you want to time: */
struct timeval timer_start, timer_end;
gettimeofday(&timer_start, NULL);

/* Put this right after the code you want to time: */
gettimeofday(&timer_end, NULL);
double timer_spent = timer_end.tv_sec - timer_start.tv_sec + (timer_end.tv_usec - timer_start.tv_usec) / 1000000.0;
printf("Time spent: %.6f\n", timer_spent);

Time it - C

This function runs another function, given as a parameter, a certain number of times and returns the number of cycles needed to complete.

Useful for timing short snippets of code.

#include <time.h>

typedef void(*FN)();

double timeit(FN f, int n) {
  clock_t start = clock();

  int i = 0;
  for (; i < n; ++i)
    f();

  return clock() - start;
}

Using Ao_timer for a better sleep

A few of my old examples include 'unsafe' use of e32.ao_sleep().
The problem is that the sleep can't be interrupted.
I often use a convenient loop like this
while running:
  // do something
  e32.ao_sleep(1)  # sleep a sec


Now in pys60 1.3.1, it's better to use e32.Ao_timer
timer = e32.Ao_timer()
while running:
  // do something
  timer.after(1)   # sleep a sec

I can then interupt the sleep with
timer.cancel()

in other part of the program if I need to continue the loop.

For example, I can end the application without waiting for
the last second.

Mobile timer app

from appuifw import *
from key_codes import *
import e32, time

class StopWatch:
    running = 0
    time_start = None
    elap = 0.0

    def __init__(self):
        self.canvas = Canvas(self.update)
        app.body = self.canvas
        self.canvas.bind(EKeySelect, self.toggle)
        self.update()

    def update(self, rect=None):
        if self.running:
            self.elap = time.clock() - self.time_start
            e32.ao_sleep(0.05, self.update)
        t = self.elap
        min = int(t / 60)
        sec =  int(t - min*60)
        hsec = int((t - min*60 - sec)*100)
        self.canvas.clear()
        self.canvas.text((20,40), u"%02d:%02d:%02d" % (min,sec,hsec), font='title')

    def toggle(self):
        if self.running:
            self.running = 0
            self.elap = time.clock() - self.time_start
        else:
            self.running = 1
            self.time_start = time.clock() - self.elap
            self.update()

    def reset(self):
        self.running = 0
        self.elap = 0.0
        self.update()


sw = StopWatch()
lock = e32.Ao_lock()
app.menu = [(u'Reset', sw.reset), (u'Close', lock.signal)]
app.exit_key_handler = lock.signal
lock.wait()

This will run and pause, resume when you press the select key.

Use timeit module

>>> from timeit import Timer
>>> t = Timer('md5.new("md5 is not safe").digest()', 'import md5')
>>> t.timeit()
2.6892227922821803

Quite useful to compare speed of codes.
Read more here
http://diveintopython.org/performance_tuning/timeit.html
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS