How can I bind a timer with infinite loops in jQuery?
I am trying to plot a progress indicator associated with a timer. For example, every second adds 1% to the bandwidth. Now I get to the part where I can press the button and it starts to progress, but this is purely arbitrary. How can I get some kind of infinite loop with jQuery to update the bar after every second? Another question, maybe a simpler one? How can I use the button to stop the progress of the bar?
Two questions
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fancy Timer </title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="javascript/jquery-1.7.2.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function ( $ ) {
last=$('ul.events li:last div').css('border', '1px solid red');
function foo(e) {
setTimeout(function() {last.animate({"width":"+=5%"})} , 1000); // delays 1.5 sec
setTimeout(function() {last.animate({"width":"+=5%"})} , 1000); // delays 1.5 sec
setTimeout(function() {last.animate({"width":"+=5%"})} , 1000); // delays 1.5 sec
setTimeout(function() {last.animate({"width":"+=5%"})} , 1000); // delays 1.5 sec
setTimeout(function() {last.animate({"width":"+=5%"})} , 1000); // delays 1.5 sec
setTimeout(function() {last.animate({"width":"+=5%"})} , 1000); // delays 1.5 sec
setTimeout(function() {last.animate({"width":"+=5%"})} , 1000); // delays 1.5 sec
setTimeout(function() {last.animate({"width":"+=5%"})} , 1000); // delays 1.5 sec
};
$("#timer").bind({
'click': foo,
});
})
</script>
<div id="wrapper">
<a href="#" id="timer">START</a>
<ul class="events">
<!-- <li style="width: 42.48%; left: 57.2%;">Design & Typography <em>(2007 - 2009)</em></li> -->
<li><div class="bar" style="width: 30%; left: 0;">Drawing & Illustration <em>(2003 - 2009)</em></div> </li>
<li><div class="bar" style="width: 55%; left: 0;">Drawing & Illustration <em>(2003 - 2009)</em></div></li>
<li><div class="bar" style="width: 45%; left: 0;">Drawing & Illustration <em>(2003 - 2009)</em></div></li>
<li><div class="bar" style="width: 10%; left: 0;">Drawing </div></li>
</ul> <!-- end .events -->
</div>
</body>
</html>
+3
source to share
3 answers
It looks like you are looking for setInterval .
var timerId = setInterval(function() {
// code you want to execute every second here
}, 1000);
// 1 second = 1000 milliseconds.
Then, when you no longer want the code to run every second, you can do:
clearInterval(timerId);
+9
source to share
function doTimeout() {
// do stuff
if (!complete) {
setTimeout(doTimeout, 1000);
}
}
// call it for the first time
setTimeout(doTimeout, 1000);
alternatively, select setInterval ()
+1
source to share