我正在制作一个随机“旋转器”,循环遍历 8 个 div 并添加一个事件类,如下所示:
https://jsfiddle.net/9q1tf51g/
//create random setTimeout time from 3sec to 5sec
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
function repeat(){
//my code
if(!exit){
setTimeout(repeat, 50);
}
}
我的问题是,我希望功能重复慢慢结束,以制造更多悬念。我想我可以通过提高超时时间 50 来做到这一点,但是我怎样才能根据剩余时间来做到这一点?
提前致谢!
最佳答案
你可以试试这个。
$('button').on('click', function(){
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var anCounter = 1;
var anState = "positive";
var exit = false;
//var time1 = 50000;
setInterval(function(){time = time-1000;}, 1000);
function repeat(){
if(anCounter>7 && anState=="positive"){ anState="negative"}
if(anCounter<2 && anState=="negative"){ anState="positive"}
$('div[data-id="'+anCounter+'"]').addClass('active');
$('div').not('div[data-id="'+anCounter+'"]').removeClass('active');
if(anState=="positive"){anCounter++;}else{anCounter--;}
if(!exit){
if(time <1000)
setTimeout(repeat, 300);
else if(time< 2000)
setTimeout(repeat, 100);
else setTimeout(repeat, 50);
}
}
repeat();
setTimeout(function(){
exit=true;
},time);
});
关于javascript - 相对于剩余时间减少 setTimeout 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37670983/