如何在使用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);
}
相关文章:
- setInteval vs setTimeout
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- setTimeout可以与闭包内的函数一起使用吗
- Javascript setTimeout for an array
- 刷新后,setTimeout将工作或不工作
- 继续使用javascript中的setTimeout
- setTimeout函数能否在其前面的代码执行之前激发
- jQuery setTimeOut: in for-loop
- SetTimeout and clearTimeout in Javascript
- 在setTimeout中调用相同的函数
- setTimeout不能太长
- Javascript-SetTimeout导致浏览器冻结
- setTimeout and V8
- 将jQuery对象传递到setTimeout递归函数中
- 是定义的操作系统睡眠/挂起期间setTimeout的行为
- 添加一个setTimeout方法会使jQuery悬停方法忽略setTimeout方法中的函数
- JS:setTimeout函数的UI计数
- 使setInterval和setTimeout工作时出现问题
- 为什么setTimeout适用于无休止的递归调用
- settimeout调用的函数未结束