js 倒计时 跳转

时间:2023-03-08 15:37:18
js 倒计时 跳转

1. setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。

setTimeout() 只执行 code 一次。如果要多次调用,请使用 setInterval() 或者让 code 自身再次调用 setTimeout()。

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>setTimeout</title>
</head>
<body>
<div id='div1'> </div> </body>
</html> <script type="text/javascript">
//设定倒数秒数
var t = ;
//显示倒数秒数
function showTime(){
t -= ;
document.getElementById('div1').innerHTML= t;
if(t==){
location.href='http://www.baidu.com';
}
//每秒执行一次,showTime()
setTimeout("showTime()",1000);
} //执行showTime()
showTime();
</script>

2.

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

<html>
<body> <input type="text" id="clock" size="" />
<script language=javascript>
var int=self.setInterval("clock()",)
function clock()
{
var t=new Date()
document.getElementById("clock").value=t
}
</script>
</form>
<button onclick="int=window.clearInterval(int)">
Stop interval</button> </body>
</html>

example :

    <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js定时跳转页面的方法</title>
</head>
<body>
<script type="text/javascript">
var t=;//设定跳转的时间
setInterval("refer()",); //启动1秒定时
function refer(){
if(t==){
location="www.baidu.com"; //#设定跳转的链接地址
}
document.getElementById('show').innerHTML=""+t+"秒后跳转"; // 显示倒计时
t--; // 计数器递减
}
</script>
<span id="show"></span>
</body>
</html>

遇到的问题:

当将上述js 的方法 放在$(function(){......})中时, 浏览器会报 methodXX() is not defined;

应当将function(){}的定义放在 <script></script>中