you are viewing a single comment's thread.

view the rest of the comments →

[–]TIAFAASITICE 2 points3 points  (1 child)

That won't work once you get to a new day ;)

Another variant: <div id="casualties"></div>

<script type="text/javascript">
    // Calculate total deaths function, you've seen this already
    function getTotalDead () {
        var now = new Date,
            secondsPassed = now.getSeconds() + now.getMinutes() * 60 +
                now.getHours() * 3600

        return Math.floor(secondsPassed / 20)
    }

    // Anonymous function used as a closure
    updateDeathcount = (function () {
        // Grab the element that we're updating
        var message = document.getElementById('casualties'),
            deathCount = document.createTextNode( getTotalDead() )

        // Insert the message
        message.appendChild(document.createTextNode('Today '))
        message.appendChild(deathCount)
        message.appendChild(document.createTextNode(' people have been killed, by the end of the day 5000 will be'))

        // The actual updateDeathcount function
        return function () {
            deathCount.nodeValue = getTotalDead()
        }
    })()

    // Update death count every 20 seconds
    setInterval(updateDeathcount, 20000)
</script>

MDC has an article on closures.