2016-05-01 7 views
0

の.jssetTimeout()の使用中に蓄積を停止する方法はありますか?

<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)) 

Iボタンをクリックすると、Djangoのビューは、JavaScriptに{{rest_time}}を与えます。その後、カウントダウンを行います(毎秒timedCount()が呼び出されます)。しかし、もう一度クリックすると、カウントダウンのスピードが溜まります。 10回クリックすると、1秒あたり10秒にカウントされます。この問題を解決するには?

+0

です:新しいものは、あなたの関数の先頭に次のように使用し、開始する前に、前のタイムアウトをクリアしますか – Sparky256

答えて

1

つのオプション:

オプション1:あなたの関数の先頭でグローバルな値を設定し 。たとえば、window.counterStartedです。

その値を設定する前に、そのグローバル値がすでに設定されているかどうかを確認してください。もしそうなら、もう一度起動しないでください。

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

オプション2: 代わりに関数内のローカル変数twindow.myTimeoutようなグローバル値にsetTimeoutを定義します。 ?セミコロン(;)標準JS文の末尾に必要な

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

ありがとう!オプション2が機能する。 – ming

+0

@ming good!コーディングで幸運を祈る! –

関連する問題