进阶11 的方方settimeout倒计时器及五道小题
2017-07-11 本文已影响18人
hhg121
http://js.jirengu.com/sinex/1/edit
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="倒计时器" />
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<select id="selectedTime" placeholder="选择一个时间">
<option value="1" selected>1分钟</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20<option>
</select>
<button id="startbutton">start</button>
<button id="pausebutton" disabled>pause</button>
<button id="resumebutton" disabled>resume</button>
<div id="outputDiv">
</div>
<script>
var timeleft;
var lasttimeId;
function showtime(){
outputDiv.textContent = timeleft + '秒';
if(timeleft > 0){
timeleft -= 1;
lasttimeId = setTimeout(showtime,1000);
}
}
startbutton.onclick = function(){
var time = parseInt(selectedTime.value,10);
seconds = time * 60;
timeleft = seconds;
if(lasttimeId){
clearTimeout(lasttimeId);
}
showtime();
pausebutton.disabled = false;
};
pausebutton.onclick = function(){
if(lasttimeId){
clearTimeout(lasttimeId);
}
pausebutton.disabled = true;
resumebutton.disabled = false;
};
resumebutton.onclick = function(){
showtime();
pausebutton.disabled = false;
resumebutton.disabled = true;
};
</script>
</body>
</html>
五道小题
for (var i = 0; i < 5; i++) {
console.log(i);
}
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, i * 1000);
}
for (var i = 0; i < 5; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, i * 1000);
})(i);
}
for (var i = 0; i < 5; i++) {
(function() {
setTimeout(function() {
console.log(i);
}, i * 1000);
})(i);
}
//光写最外面的参数,对立即执行函数无用,需要两个都写才行。
for (var i = 0; i < 5; i++) {
setTimeout((function(i) {
console.log(i);
})(i), i * 1000);
}
//立即执行函数会立即执行,0-4五个数会直接输出