码迷,mamicode.com
首页 > 其他好文 > 详细

setInterval和setTimeout定时器

时间:2014-11-03 14:16:02      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   java   sp   div   on   

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>

 

setInterval和setTimeout定时器

标签:style   blog   io   color   ar   java   sp   div   on   

原文地址:http://www.cnblogs.com/valiant1882331/p/4070933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!