我有一個社交流,我想更新setInterval。當某人離開評論或回覆時,需要停止SetInterval,否則它將清除textarea的內容,因爲它嵌套在正在更新的內容中。如何setInterval準備就緒,在textarea焦點停止,然後開始在textarea焦點?
我試圖從另一個答案使用此代碼,修改,但它是失敗的,它不會停止setInterval計時器的第一個週期後的計時器。
HTML ...
<div id="social_stream_content">
<textarea id="comments" rows="4" cols="50" placeholder="Set focus to stop timer"></textarea>
</div>
JS ...
function auto_load(){
data = '<textarea id="comments" rows="4" cols="50" placeholder="Set focus to stop timer..."></textarea>';
$("#social_stream_content").html(data);
alert("auto_load invoked");
}
var myInterval;
var interval_delay = 10000;
var is_interval_running = false; //Optional
$(document).ready(function(){
auto_load(); //Call auto_load() function when document is Ready
//Refresh auto_load() function after 10000 milliseconds
myInterval = setInterval(interval_function, interval_delay);
$('textarea').focus(function() {
console.log('focus');
clearInterval(myInterval); // Clearing interval on window blur
is_interval_running = false; //Optional
}).focusout(function() {
console.log('focusout');
clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yet
if (!is_interval_running) //Optional
myInterval = setInterval(interval_function, interval_delay);
});
});
interval_function = function() {
is_interval_running = true; //Optional
// Code running while textarea is NOT in focus
auto_load();
}
編輯:我已經更新了代碼,包括一切作爲的jsfiddle測試。如果在文檔準備就緒後關閉警報後立即將焦點置於註釋textarea,計時器將停止。
取消焦點後,間隔計時器的第一個週期結束後,計時器不會再次停止。焦點事件似乎停止發射。
這是因爲評論textarea嵌套在正在更新的內容區域內嗎?我正在拉我的頭髮。如果我刪除嵌套,它會按預期工作。
我需要注意的就是註釋文字區域總是會被嵌套在社會流的內容div中,出於顯而易見的原因。
因此,要進一步更新的問題:有沒有辦法讓間隔計時器停止對使用jquery textarea的焦點,而聚焦元素嵌套在更新元素裏面?爲什麼在第一個時間間隔完成後焦點事件停止觸發?
編輯:完整的JS代碼,coreectly工作,與傑里米Klukan的解決方案結合,爲任何人做同樣類型的項目。
工作JS:
function auto_load(){
data = '<textarea id="comments" rows="4" cols="50" placeholder="Set focus to stop timer..."></textarea>';
$("#social_stream_content").html(data);
alert("auto_load invoked");
}
var myInterval;
var interval_delay = 10000;
var is_interval_running = false; //Optional
$(document).ready(function(){
auto_load(); //Call auto_load() function when document is Ready
//Refresh auto_load() function after 10000 milliseconds
myInterval = setInterval(interval_function, interval_delay);
$('body').on('focus', '#social_stream_content textarea', function (event) {
console.log('focus');
clearInterval(myInterval); // Clearing interval on window blur
is_interval_running = false; //Optional
}).on('focusout', '#social_stream_content textarea', function(event) {
console.log('focusout');
clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yet
if (!is_interval_running) //Optional
myInterval = setInterval(interval_function, interval_delay);
});
});
interval_function = function() {
is_interval_running = true; //Optional
// Code running while textarea is NOT in focus
auto_load();
}
鏈接到JSfiddle,我測試... https://jsfiddle.net/a60nj1pf/ –