停止coffeescript中的setInterval [英] Stopping setInterval in coffeescript
问题描述
如何在我的脚本中停止setInterval?警告工作, clearInterval
不,并且控制台中没有任何错误。
How can I stop the setInterval in my script ? Alert working, clearInterval
not, and there isn't any error in console.
order =
start_poll: ->
interval = setInterval(@request, 60000)
stop_polling: ->
clearInterval order.start_poll()
alert ('expired')
request: ->
id = $('#status_id').attr('data-id')
$.get "/orders/#{id}", (data) ->
console.log("#{data.status}")
if data.status is 'expired'
order.stop_polling()
$ ->
order.start_poll()
推荐答案
setInterval
在每次调用它时返回一个新的计时器ID,并传递该ID clearInterval
停止该特定计时器。所以当你这样做:
setInterval
returns a new timer ID every time you call it and you pass that ID clearInterval
to stop that specific timer. So when you do this:
clearInterval order.start_poll()
你只是开始一个新的计时器,并立即停止它,这将不会对其他计时器产生任何影响。
you're just starting a new timer and immediately stopping it, this won't have any affect whatsoever on other timers.
您需要存储ID,以便以后可以取消ID:
You need to store the ID so that you can cancel it later:
order =
start_poll: ->
@interval = setInterval(@request, 60000)
stop_polling: ->
clearInterval(@interval) if(@interval)
alert('expired')
#...
您可能需要向 start_poll $ c>的顶部添加
@stop_polling()
$ c>。这是没有必要的,但它不会伤害,它将有助于防止未来的错误,如果你决定改变如何与投票互动。
You might want to add a @stop_polling()
call to the top of start_poll
too. This isn't necessary but it can't hurt and it will help prevent future bugs if you decide to change how you interact with the polling.
这篇关于停止coffeescript中的setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!