我有代码(它是有效的),但我需要:1.点击(".mydiv")后,函数应该停止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);
};;
代码总是有效的,我不知道如何修复它。
我不太确定你想要实现什么,但你可以试试这个逻辑:
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();
您可以使用函数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?