[Tutor] timed functions? Timeouts?
W W
srilyk at gmail.com
Mon May 19 23:28:47 CEST 2008
Hi, I'm having trouble finding any information (or if it's possible)
on this particular topic.
Specifically, there's a feature in javascript that I want to emulate.
this is an example I pulled from a webmonkey tutorial
--------------------------
function writeTime() {
// get a date object
var today = new Date();
// ask the object for some information
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
// fixTime makes the minutes and seconds look right
// it just sticks a zero in front of numbers less than 10
minutes = fixTime(minutes);
seconds = fixTime(seconds);
// put together the time string and write it out
var the_time = hours + ":" + minutes + ":" + seconds;
window.document.the_form.the_text.value = the_time;
// run this function again in half a second
the_timeout= setTimeout('writeTime();',500);
}
function fixTime(the_time) {
if (the_time <10)
{
the_time = "0" + the_time;
}
return the_time;
}
---------------
The specific bit I'm looking at is this line
the_timeout = setTimeout('writeTime();',500);
basically it calls the function again in 500ms, but rather than
pausing, I guess it spawns a new thread? I'm not really sure.
>From the little experience I have in JS it appears that multiple
"timers" can be running at a time, all the code "in between" the
timeouts will execute, and when the timeout is finished it will
execute whatever the command is (in this case, 'writeTime();').
So I'm trying to find out a pythonic equivalent (if there is one). So
far Googling for "python timeout" gives me no helpful results, and
"python threading" gives me some examples that are close to what I
think I'm looking for.
Now, when I look at that example and try to translate the timeout to
what I think is going on "behind the scenes" I'm pretty sure it spawns
a thread that does something similar to this:
1 import time
2
3 def timer(end, exe):
4 start = time.time()
5 while True:
6 now = time.time()
7 if (now - start) >= end:
8 break
9 exe()
10
11 def execute_this():
12 for x in range(1, 10):
13 print x
14
15 timer(5, execute_this)
Am I correct? Is there a python built-in for this? Where should I go
to learn more? Is there anything "wrong" with using a function like
this?
Thanks in advance,
Wayne
--
To be considered stupid and to be told so is more painful than being
called gluttonous, mendacious, violent, lascivious, lazy, cowardly:
every weakness, every vice, has found its defenders, its rhetoric, its
ennoblement and exaltation, but stupidity hasn't. - Primo Levi
More information about the Tutor
mailing list