2

I'm using MVC with some partial rendering and ajax calls. In one of my result tables I have a field that is a timer.

The following code is on my partial view that is rendered every 30 seconds. One of the fields is an active timer that displays to the user:

<td><div id="@someID" class="nobutton"></div><script>setInterval(function () { startTimer('@startDateTime', '@someID') }, 500);</script></td>

This works great but after the ajax call is made to refresh the partial, the interval function is still calling the old IDs (someID) that are no longer there.

Here is the javascript for the timer:

<script type="text/javascript">
    function startTime(dt, field){
        var field = document.getElementById(field);
        if (field == null)
            return;

        var rowTime = new Date(dt);
        var rowTimems = rowTime.getTime(rowTime);

        var currentTime = new Date();
        var currentTimems = currentTime.getTime(currentTime);

        var difference = currentTimems - rowTimems;

        var hours = Math.floor(difference / 36e5),
            minutes = Math.floor(difference % 36e5 / 60000),
            seconds = Math.floor(difference % 60000 / 1000);

        field.innerHTML = formatTime(hours) + ":" + formatTime(minutes) + ":" + formatTime(seconds);
</script>

And the call on the main page that refreshes the partial is pretty simple:

var t = setInterval(function () {
            $.ajax({
                url: "MYURL",
                type: "GET",
                cache: false,
                success: function (data) {
                    $("#summary").html(data);                    
                }
            });
        }, 30000);

Is there a way to kill the old timers? Why are they still running?

4

2 に答える 2