我在stackoverflow中找到了这段代码,但我仍然在问自己计时器是如何自动启动第一次的。
但是我注意到对此发表评论:
//Optionally, activate each timer:
//restart(i)();
将阻止计时器自动启动。
它可能是一个自动执行的功能,如果是的话。即使在这种情况下仍未单击按钮,自动执行功能是否会始终自动启动?
我还看到函数内部还有其他可能是自动执行的函数,有人可以解释一下这是如何工作的。
<!DOCTYPE html PUBLIC>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
</head>
<body>
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count0">0</span>
<input type="submit" name="increment" value="Increment" />
<br />
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count1">0</span>
<input type="submit" name="increment" value="Increment" />
<br />
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count2">0</span>
<input type="submit" name="increment" value="Increment" />
<br />
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count3">0</span>
<input type="submit" name="increment" value="Increment" />
<br />
<input type="submit" name="clear" value="Stop Timer" />
<input type="submit" name="reset" value="Restart Timer" />
<span id="count4">0</span>
<input type="submit" name="increment" value="Increment" />
<script>
(function(){ //Anonymous function, to not leak variables to the global scope
var defaultSpeed = 3000; //Used when missing
var timerSpeed = [500, 1000, 2000, 4000, 8000];
var intervals = [];
function increase(i){
return function(){
var elem = $("#count"+i);
elem.text(parseInt(elem.text()) + 1);
}
}
function clear(i){
return function(){
clearInterval(intervals[i]);
}
}
function restart(i){ //Start AND restart
return function(){
clear(i)();
increase(i)();
intervals[i] = setInterval(increase(i), timerSpeed[i]||defaultSpeed);
}
}
// Manual increment
$('input[name=increment]').each(function(i){
$(this).click(function(){
restart(i)();
increase(i)();
});
});
// Clear timer on "Clear"
$('input[name=clear]').each(function(i) {
$(this).click(clear(i));
});
// Restart timer on "Restart"
$('input[name=reset]').each(function(i) {
$(this).click(restart(i));
//Optionally, activate each timer:
restart(i)();
});
})();
</script>
</body>
</html>