I'm looking for plugin or jQuery to do following:
- count time - in minutes & seconds from 0.
- start count on page load = start counting fr开发者_运维技巧om 0 every reload
Any help much appreciated.
I knocked up something very simple to satisfy just such a requirement. Get it at https://github.com/robcowie/jquery-stopwatch and see a demo at http://jsfiddle.net/rob_cowie/Pt9nc/
In pure javascript, you can do this, to an extent:
The timer is simple. On page load, store a reference to the current time, and then periodically update some field, showing the difference in time between now and then.
var startTime = new Date(), outputDiv = document.getElementById('output') // or $('#output').get(0) ; setInterval(function () { outputDiv.innerHTML = "ms since the start: " + (new Date() - startTime); }, 1000);
I'll leave it as an exercise to the reader to fill in the time formatting to mm:ss or whatever.
The page counter is slightly more complicated since Javascript itself doesn't persist between page refreshes. You'll need to find some way to persist the data. The old way would be to use cookies, but with HTML5, a better solution would be to use
sessionStorage
, which has pretty good browser support. You can read more about it on the Mozilla documentation.The basic flow would be this:
- Check for your variable name in sessionStorage (let's say
"myPageCounter"
)- if it doesn't exist, the counter value is 0;
- if it does exist, grab the value
- Add 1 to the value.
- Store it back into
sessionStorage
, ready for the next page load.
- Check for your variable name in sessionStorage (let's say
Why not using pure javascript timing events.
Some examples here:
http://www.w3schools.com/js/js_timing.asp
Even one that counts in seconds. I have adapted it here below to count minutes as well:
<html>
<head>
<script type="text/javascript">
var c=0;
var minutes= 0;
var t;
var timer_is_on=0;
function timedCount()
{
document.getElementById('txt').value='minutes:'+ minutes + ' seconds: '+ c;
c=c+1;
if (c%60==0){
minutes+=1;
c=0;
}
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
</form>
<p>Click on the button above. The input field will count forever, starting at 0.</p>
</body>
You may try the countdown plugin. You could use the since
or until
properties to specify whether it should count down or up.
精彩评论