我有代码(这是工作),但我需要: 1.单击(“.my div”)后,函数应该停止 2.该功能应在可变时间段后开始(可能是10秒,15,5,30)。
jQuery(document).ready(function($) {
if (document.getElementById("monitor") !== null){
var counter = 200;
var myFunction = function(){
clearInterval(interval);
counter *= 10;
interval = setInterval(myFunction, counter);
};
var interval = setInterval(myFunction, counter);
setInterval(function() { Piano.anim(); }, interval);
}
Piano.anim = function(){...},1000);
};;
代码始终有效,我不知道如何修复它。
答案 0 :(得分:0)
你可以使用函数clearInterval(),然后创建一个新的间隔,在setTimeout()
一段时间后重复它var interval = setInterval(myFunction, counter);
//after clicking the .my div
clearInterval(interval);
var second_interval = setInterval(myFunction, counter);//Maybe an other function than myFunction?
答案 1 :(得分:0)
我不确定你想要实现的目标,但你可以尝试这个逻辑:
var interval = null;
// the function to be called each second
function x(){
console.log('running');
}
//start interval
function startInterval(){
interval = setInterval(x, 1000);
}
// called at (".my div") click
// stop the interval, then restart it after 10 seconds
// save the timeout so it's not called more than once
var restartTimeout = null;
function interruptInterval(){
if(interval && !restartTimeout){
clearInterval(interval);
restartTimeout = setTimeout(startInterval, 10000);
}
}
$(".my div").click(interruptInterval);
startInterval();