setTimeout() 函数本身是异步的,理论上不会阻塞当前线程往下运行(这并不表示setTime() 中函数的执行不会对当前线程造成影响)。跟其并排的其他 setTimeout() 函数会异步执行,setTimeout() 中的函数会在设定好的延迟执行。
计时跳转
setTimeout(function () {
window.location.href = "/";
},3000)
重复执行(内部setTimeout() 调用好几次,外部的setTimeout() 只调用一次。
setTimeout(function() {
setTimeout(arguments.callee,interval);
//需要3秒种执行一次的代码
},interval);
内部的 setTimeout() 获取当前执行的匿名函数,并每隔 interval时间,执行所在函数的代码块。3s -- 3s --3s ....
定义一个匿名函数(实际上是一个函数表达式),并立即调用这个匿名函数。
(function () {
if (interval > 0) {
setTimeout(arguments.callee, 1000);
$('em').text(interval);
interval--;
}
})();
最后的代码是这个
(function () {
if (interval > 0) {
setTimeout(arguments.callee, 1000);
$('em').text(interval);
interval--;
} else {
window.location.href = "/";
}
})();
或者多计时1秒
setTimeout(function () {
if (interval > 0) {
setTimeout(arguments.callee, 1000);
$('em').text(interval);
interval--;
} else {
window.location.href = "/";
}
}, 1000);
完整示例
<html lang="en">
<head>
<meta charset="UTF-8">
<title>无内容</title>
</head>
<body>
未找到结果, <span id="secound">3</span> 秒后跳转到首页
<script type="text/javascript">
var sec = document.getElementById("secound")
var interval = parseInt(sec.innerText);
(function () {
if (interval > 0) {
setTimeout(arguments.callee, 1000);
sec.innerText = interval;
interval--;
} else {
window.location.href = "/";
}
})();
</script>
</body>
</html>
233