您的位置:首页 > 其它

setTimeout与setInterval区别

2015-11-26 22:12 357 查看
参考Mecry的博客,网址:http://www.cnblogs.com/mercy/articles/2424882.html

function test(){

console.log("hello world!");

}

var id=setTimeout(test,5000); //可以使用函数名test来作为参数,此时函数名不可以带参数

//setTimeout("test()",2000); //可以使用字符串来作为参数,可以带参数

clearTimeout(id);

console.log("取消该setTimeout事件,此时该事件的ID="+id);



//var id=window.setInterval(test,1000);

//window.clearInterval(id); //取消定时执行



console.log("函数带参数的书写!");

function testTwo(name){

console.log("hello world! "+name);

}

//window.setTimeout(testTwo("zhou"),3000);//此种写法,无法实现延迟效果,直接就执行了。

//window.setTimeout("testTwo(\"zhou\")",3000); //可以实现延迟效果



function testThree(name){

return function(){

console.log("hello world! "+name);

};

}

window.setTimeout(testThree("ma"),3000); //testThree("ma")被看成一个不带参数的函数,因为其返回就是

//不带参数的函数function,故可以执行延迟效果


<body>

<form action="#">

<input type="text" value="0" name="txt1" />

<input type="button" value="开始" name="btnStart" />

<input type="button" value="重置" name="btnReset" />

</form>

<script type="text/javascript">

console.log("秒表的工作展示:");

//获取表单中的表单域

var txt = document.forms[0].elements["txt1"];

var btnStart = document.forms[0].elements["btnStart"];

var btnReset = document.forms[0].elements["btnReset"];

console.log(txt.value+" "+btnStart.value+" "+btnReset.value);

//定义定时器的id

var id;

//每10毫秒该值增加1

var seed = 0;

btnStart.onclick = function() {

//根据按钮文本来判断当前操作

if (this.value == "开始") {

//使按钮文本变为停止

this.value = "停止";

//使重置按钮不可用

btnReset.disabled = true;

//设置定时器,每0.01s跳一次

id = window.setInterval(tip, 10);

}else {

//使按钮文本变为开始

this.value = "开始";

//使重置按钮可用

btnReset.disabled = false;

//取消定时

window.clearInterval(id);

}

};

//重置按钮

btnReset.onclick = function() {

seed = 0;

txt.value=seed;

};

//让秒表跳一格

function tip() {

seed++;

txt.value = seed / 100;

}

</script>

</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: