setInterval和setTimeout定时器

时间:2023-03-08 21:34:28

1,文本框自增(重零开始)每隔一秒递增1

<input type="text" name="name" value="0" id="txt" />
<script type="text/javascript">
window.onload = function () {
setInterval(function () {
//获取文本框对象
var obj = document.getElementById('txt');
//获取value值
var txtvalue = parseInt(obj.value);
obj.value = txtvalue = txtvalue + 1;
},1000);
}
</script>

计时器setInterval会返回一个计时器id,可以用来清除计时器

function f1() {
alert('嘎嘎');
}
//计时器,返回值是该计时器的id
var setId = window.setInterval(f1, 2000);
//清除计时器方法,参数是一个计时器的id,清除计时器
window.clearInterval(setId);

2,setTimeout(这个计时器就执行一次)

//这个计时器就执行一次
var setId= setTimeout(function () {
alert('加载了');
}, 1000);
clearTimeout(setId);//清除计时器

例子:标题栏跑马灯

<input type="button" name="name" value="向左走" id="btnLeft" />
<input type="button" name="name" value="向右走" id="btnRight" />
<script type="text/javascript">
var def = 'left';
function f1() {
def = 'left';
}
function f2() {
def = 'right';
}
window.onload = function () {
setInterval(function () {
//获取标题内容
var tit = document.title;
if (def == 'left') {
document.title = tit.substr(1) + tit.charAt(0);
} else if (def == 'right') {
document.title = tit.charAt(tit.length - 1) + tit.substr(0, tit.length - 1);
}
}, 1000);
document.getElementById('btnLeft').onclick = f1;
document.getElementById('btnRight').onclick = f2;
};
</script>