学习之旅 第一篇 javascript setTimeout和setInterval

来源:互联网 发布:php简单商城源代码 编辑:程序博客网 时间:2024/05/24 00:02

       javascript 中有两个函数以前一直没有搞明白区别 setTimeout和setInterval 他们两个的功能都一样的!都是隔一段时间,触发指定的代码.这两个函数都需要两个参数

参数一是执行的函数对象,或者是内容.

参数二是时间以毫秒为单位.

 不同之处在于setTimeout函数执行一次.setInterval函数会循环一直执行下去.

 

测试代码 一

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script type="text/javascript">
function timedMsg()
{
    var t = setInterval("alert('5 seconds!')", 5000)
}
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Display timed alertbox!"
onClick="timedMsg()">

    </div>
    </form>
</body>
</html>

测试代码二

 

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script type="text/javascript">
function timedMsg()
{
    var t = setTimeout("alert('5 seconds!')", 5000)
}
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Display timed alertbox!"
onClick="timedMsg()">

    </div>
    </form>
</body>
</html>

 

clearInterval 和clearTimeout 这两个函数是相对与setInterval 和setTimeout 取消执行的. clearInterval,clearTimeout函数都需要一个对象,但是不是被执行的函数的对象.

而是 setInterval,setTimeout函数的对象. setInterval和clearInterval 是一对,setTimeout和clearTimeout是一对

我之前的 错误使用代码一

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script type="text/javascript">
function timedMsg()
{

var funtest=Test();
 var t = setInterval(funtest, 5000)

//错误代码

clearInterval(funtest);

//正常的代码

clearInterval(t);


}

function Test()

{

alert('5 seconds!');

}
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Display timed alertbox!"
onClick="timedMsg()">

    </div>
    </form>
</body>
</html>

第一次在 csdn上写博文,还请大师们多多指教