Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>element</code> in the script is the id of the tag you pass to the function.<br> So <code>countdown('div1')</code> will show a timer in a tag with id="div1"</p> <p>However your particular timer does not allow multiple instances and uses a global var called interval. </p> <p>Generate the JSON on the server and the rest takes care of itself</p> <p>HERE is an OO version that is more precise since it is only calculating the end time instead of relying on interval which will block if the browser is busy: <a href="http://jsbin.com/ujuzo5/edit" rel="nofollow noreferrer">http://jsbin.com/ujuzo5/edit</a></p> <p>And here is my original solution with the help of the good folks at SO here: <a href="https://stackoverflow.com/questions/4584845/broken-closure-please-help-me-fix-it">Broken closure - please help me fix it</a></p> <pre><code>&lt;script type="text/javascript"&gt; // generate this on the server and note there is no comma after the last item var counters = { "shoes":{"id":"shoe1","minutes":1,"seconds":5}, "trousers":{"id":"trouser1","minutes":10,"seconds":0} }; var intervals = {}; window.onload = function() { for (var el in counters) { countdown(counters[el]) }; } function countdown(element) { var minutes = element.minutes; var seconds = element.seconds; intervals[element.id] = setInterval(function() { var el = document.getElementById(element.id); if(seconds == 0) { if(minutes == 0) { el.innerHTML = "countdown's over!"; clearInterval(intervals[element.id]); return; } else { minutes--; seconds = 60; } } if(minutes &gt; 0) { var minute_text = minutes + (minutes &gt; 1 ? ' minutes' : ' minute'); } else { var minute_text = ''; } var second_text = seconds &gt; 1 ? 'seconds' : 'second'; el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining'; seconds--; // optionally update the member values element.minutes=minutes; element.seconds=seconds; }, 1000); } &lt;/script&gt; shoes: &lt;span id="shoe1"&gt;&lt;/span&gt;&lt;br /&gt; trousers: &lt;span id="trouser1"&gt;&lt;/span&gt;&lt;br /&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload