SetTimeOut 和 SetInterval小記

发现有段时间没有应用到 SetTime 和 SetInterver , 特別記錄一下~~~~~

一、setTimeout, 在指定时间后执行一次,例如:

var timerId = setTimeout(func|code, delay)
上面代码中,setTimeout函数接受两个参数,第一个参数func|code是将要推迟执行的函数名或者一段代码,第二个参数delay是推迟执行的毫秒数。
注:如果把delay 設置為0,表示尽可能早地执行指定的任务,也就是說它可能不會立即執行(如果隊隊列中還有其它任務)。html5中會把0默認為4毫秒,目的是為了防止過多的執行導致性能問題。

<script>  
//定时器 异步运行  
function hello(){  
alert("hello");  
}  

var t1 = window.setTimeout(hello,1000);  //使用方法名字执行方法,注意函數名后不要加()  
var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法  
window.clearTimeout(t1);//去掉定时器  
</script>   

如果要循环,可以用递归在函数内调用自已。例如:60秒倒数

  var  seconds = 60;       
        function FuncSetTimeOut() {           
            seconds = seconds - 1;           
            $("#span1").text(seconds)
            var var1 = setTimeout(FuncSetTimeOut, 1000);
            if (Number(seconds) == 1) {
                clearTimeout(var1);
            }
        }

二、SetInterval , 每隔一段時間進行循環執行。

例如:60秒倒数

  function FunSetInterval() {
            seconds = seconds - 1;
            $("#span1").text(seconds)          
            if (Number(seconds) == 1) {
                clearInterval(interval1);
            }
        }
        $(function () {           
            interval1= setInterval(FunSetInterval, 1000);//每隔一秒執行函數FunSetInterval, 也是注意不要加函數后面不要加() 
        }
        );
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值