私は動的に更新しているタイマーを持っています。timerを動的に更新する際のclearTimeout
------------------更新-------------------------- 最初に質問を投稿したときに、タイマーがバックボーンビューから呼び出されているとは思えませんでしたが、その結果、グローバル変数(または少なくともグローバル変数動作していません)。私は複数のタイマーを呼び出すので、グローバル変数を1つだけ設定して削除することはできません。私は、他のものをクリアすることなく1つのタイマーをクリアすることができる必要があります。
私はタイマーを開始、私のアプリで
function countDown(end_time, divid){ var tdiv = document.getElementById(divid), to; this.rewriteCounter = function(){ if (end_time >= MyApp.start_time) { tdiv.innerHTML = Math.round(end_time - MyApp.start_time); } else { alert('times up'); } }; this.rewriteCounter(); to = setInterval(this.rewriteCounter,1000); }
、私は
MyApp.Views.Timer = Backbone.View.extend({ el: 'div#timer', initialize: function(){ timer = this.model; this.render(); }, events: { "clicked div#add_time": "update_timer" } render: function(){ $(this.el).append(HandlebarsTemplates['timer'](timer); this.start_timer(); }, start_timer: function(){ delete main_timer; // this doesn't work :( clearTimtout(main_timer); //this doesn't work either :( var main_timer = setTimeout(new countDown(timed.length, 'main_timer'),timed.length*1000); }, update_timer: function(){ timed.length=timed.length+30 this.start_timer(); } });
とバックボーンビューでタイマーを開始するので、私がやろうとしていることは、タイマーを更新することです古いタイマーを終了し、新しい値で再起動します。私は異なるタイマーを持っているので、カウントダウン機能内でtimed.length
を呼び出すだけでは機能しません。
であなたは 'のsetTimeout(から返された値を保持するために、グローバル変数を必要とすることに注意してください)'。 'setTimeout()'によって返された値でdeleteを呼び出すことはできません。また、 'clearTimtout()'で行ったスペルミスに注意してください。さらに、関数が存在した後に値が保存されない 'start_timer()'関数でmain_timerをローカル変数として再宣言しています。 – Yaniro
ありがとうYaniro、私は質問を更新しました。 – pedalpete