我有一个我从背景改编的屏幕保护程序。但是,唯一的问题是屏幕保护程序在完成错误之前只能运行一次或两次:Too much recursion
我读到这是来自'冒泡'的触发器,但我不知道如何防止它。我现在已经重复了几次代码。
等待十秒钟以启动屏幕保护程序移动鼠标以停止它,通常会出现错误。
错误
too much recursion jquery.min.js:2
http://codepen.io/WAS/pen/fuHLn
var i = 0,
screensaver = $('#screensaver'),
startTime = 100,
isOff = true;
function countit () {
if ( i >= startTime && isOff == true ) {
screensaver.fadeIn('slow', function() {
isOff = false;
});
}
screensaver.bind('mousemove', function(e){
i=0;
screensaver.fadeOut('fast');
});
i++;
}
$(window).ready(function(){
var screensaver = setInterval(countit, 100);
});
答案 0 :(得分:1)
一个主要问题是您在一个区间内绑定一个事件处理程序。在100ms
期间,将向元素添加新的事件处理程序。
另一个问题是,你没有重置布尔值。
您可以尝试以下操作:
var screensaver = $('#screensaver'),
startTime = 5000,
timeout = null,
isOff = true;
function timer() {
if (!timeout && isOff) { // if no timer exists and screensaver is off, start one
timeout = setTimeout(function () {
screensaver.fadeIn('slow', function () {
isOff = false; // screensaver active
});
}, startTime);
}
}
$(document).ready(function () {
var interval = setInterval(timer, 1000); // keep checking for timer every 1s
screensaver.bind('mousemove', function (e) {
if (timeout) { // if a timer is running, clear it
clearTimeout(timeout);
timeout = null;
}
if (!isOff) { //if the screensaver is active, hide it
screensaver.fadeOut('fast', function () {
isOff = true; // screensaver inactive
});
}
});
});
body {
padding:0;
margin:0;
overflow:hidden;
height: 600px;
background-color: #1A1A1A;
}
p {
color:white;
}
#screensaver {
display: none;
position: absolute;
top: 0;
right:0;
bottom:0;
left: 0;
width:100%;
height:100%;
background-color: dodgerblue;
}
#screensaver div{
position: absolute;
top: 0;
right:0;
bottom:0;
left: 0;
width: 200px;
height: 100px;
line-height:100px;
margin:auto;
text-align:center;
color:#fff;
background-color: hotpink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="screensaver"><div>Screensaver</div></div>
<br />
<p align="center">Forums and stuff here....
</p>
(等待5秒以激活屏幕保护程序并将鼠标移到结果窗口中以解除它)