简体   繁体   中英

Python timer similar to javascript timer

I want to create a dynamic timer on webpage in python like this code which is in Javascript:

<script language="JavaScript" type="text/javascript">
var seconds = 40;   
var minutes = 01;   
function timer() {seconds--;
  if (seconds == -01) {
   seconds = 59;
   minutes = minutes - 1; }
  else {
   minutes = minutes; }
if (seconds<=9) { seconds = "0" + seconds; }
 time = (minutes<=9 ? "0" + minutes : minutes) +":"+seconds;
if (document.getElementById) { document.getElementById('timertable').innerHTML = time; }
timeout=window.setTimeout("timer();", 1000);
if (minutes == '00' && seconds == '00') { seconds = "00"; window.clearTimeout(timeout); }
}
window.onload = timer;
</script>

Some of the conditions the timer must satisfy are: 1>Timer should not re-initialize its value once the other contents of the page reload 2>The duration for which the timer is supposed to run is coming from another HTML page on the basis of choice made by user Please note that I am using Django on google app engine. Please let me know if I am not clear.Thanks, Sunil

This isn't quite possible in python, as python is server side, and you are displaying user side data. You won't get around javascript in any way, either you will need the timer itself on the js side or you'd need ajax.

I am still unsure about what you are trying to achieve.

You may use cookies to store the timer state and initialize the timer following the values present in cookies.
W3School tutorial on cookies: http://www.w3schools.com/JS/js_cookies.asp

If you have a timer which is set up at your server level, you may use an ajax view to fetch the inital time from server and another one to update time as the js timer progresses. You may decrease the requests frequency (maybe 1 per 5 seconds) with the cost of some time loss.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM