如何在使用setTimeout()时停止累积

how to stop the accumulation while using setTimeout()?

本文关键字:setTimeout      更新时间:2023-09-26

.js

<script type="text/javascript">
var c={{ rest_time }}
var t
function timedCount()
{
    if(c>-1){
        $('#txt').html(c)
        c=c-1
        t=setTimeout("timedCount()",1000)    //1000ms后,执行参数1(调用自身)
    }
    else{
        $('#txt').html("time's up")
    }
}
$(document).ready(timedCount())
</script>

django视图

def show_reply_page(request, topic_id):
    t = topic.objects.get(id=topic_id)
    comments = t.comment_set.filter(deleted=False)
    posts = t.post_set.filter(deleted=False)
    past_time = int(time.time() - t.locktime)
    rest_time = 300 - past_time
    t.save()
    return render_to_response('forum/reply.html', {'conf': conf, 'title': t.title,
                                             'request': request,
                                             'topic': t,
                                             'posts': posts,
                                             'comments': comments,
                                             'past_time': past_time,
                                             'rest_time' : rest_time,
    },
                              context_instance=RequestContext(request))

当我单击按钮时,django视图将为javascript提供{{rest_time}}。然后它会倒计时(每隔一秒dCount()调用自己)。但当我再次点击它时,倒计时的速度就会累积起来。这意味着当我点击它十次时,它的计数是每秒10秒。如何更正此问题?

两个选项:

选项1:在函数的开头设置一个全局值。例如CCD_ 1。

但即使在设置该值之前,也要检查该全局值是否已设置。如果是,那么就不要再启动它。

if(typeof window.counterStarted !== undefined){
    return false;
}
window.counterStarted = true;

选项2:setTimeout定义为全局值,如window.myTimeout,而不是函数中的局部变量t。然后,要在新的超时开始前清除前一个超时,请在函数的开头使用以下内容:

if(typeof window.myTimeout !== undefined){
    clearTimeout(window.myTimeout);
}