发光的CSS效果是:
//Public Variables.
var clear_interval;
var stop_set_time_out;
function record_css_effect() {
clear_interval = setInterval(
function() {
rec_block.css('background-color', "red");
stop_set_time_out = setTimeout(function() {
rec_block.css('background-color', "green");
}, 500)
}, 1000);
};
在另一个函数中,我调用:
function stop_record() {
alert("Stop record.");
clearTimeout(stop_set_time_out);
clearInterval(clear_interval);
}
发光只在第一次停止。
第二次,我没有调用
record_css_effect()
函数,但是发光效果自动发生了...这意味着
clearTimeout
和clearInterval
不起作用...为什么会这样,我如何实现呢?
更新:
实际上,我使用clearInterval(clear_interval);在很多地方。
当用户想要记录时,他们按下按钮,然后调用pop_record_window()。
function pop_record_window()
{
$('#start_and_stop_rec').click
(
function(){ record_voice(); }
)
}
function record_voice()
{
record_css_effect();
REC= $("#start_and_stop_rec");
if(REC.prop("value")=="record")
{
alert("Start to record");
alert( dir_path + User_Editime + "/rec"+"/" + "P" + current_page + "_" + records_pages_arr[current_page].get_obj_num() +".mp3");
current_rec_path= dir_path + User_Editime + "/rec"+"/" + "P" + current_page + "_" + records_pages_arr[current_page].get_obj_num() +".mp3";
cur_record_file= new Media(current_rec_path,onSuccess, onError);
cur_record_file.startRecord();
$('#stop_rec').bind("click", function(){
clearTimeout( stop_set_time_out );
clearInterval( clear_interval );
});
REC.prop("value","stop");
}
else if(REC.prop("value") == "stop")
{
stop_record();
cur_record_file.stopRecord();
clearInterval( clear_interval );
//make visibility hidden!
REC.prop("value","record");
}
};
但是自从第二次以来,用户就没有按下按钮:start_and_stop_rec,就会发出发光效果。但是,其中的代码
if(REC.prop(“ value”)==“ record”)条件不执行。
最佳答案
如果多次调用record_css_effect()
,则可能会启动多个间隔,但是只有最后一个间隔ID将存储在clear_interval
中。通过确保一次仅运行一个间隔,您可以防止这种情况的发生。
//Public Variables.
var clear_interval;
var stop_set_time_out;
function record_css_effect() {
if (clear_interval !== null) // if a timer is already returning don't start another
return;
clear_interval = setInterval(function () {
rec_block.css('background-color', 'red');
stop_set_time_out = setTimeout(function () {
rec_block.css('background-color', 'green');
}, 500)
}, 1000);
};
function stop_record() {
alert("Stop record.");
clearTimeout(stop_set_time_out);
clearInterval(clear_interval);
stop_set_time_out = clear_interval = null;
}
您还可以使代码更简单(通过删除
setTimeout
),使其更易于调试,如下所示://Public Variables.
var clear_interval, isRed = false;
function record_css_effect() {
if (clear_interval !== null) // if a timer is already returning don't start another
return;
clear_interval = setInterval(function () {
if (isRed) {
rec_block.css('background-color', 'red');
isRed = false;
} else {
rec_block.css('background-color', 'green');
isRed = true;
}
}, 500);
};
function stop_record() {
alert("Stop record.");
clearInterval(clear_interval);
clear_interval = null;
}?