使用jquery的delay方式模拟sleep

javascript中并没有原生sleep函数可供调用,一般来说为了实现sleep功能,大都是采用SetTimeout来模拟,以下片段采用jquery的delay方法来模拟,也算是提供了另外一个视角吧

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delay demo</title>
<style>
div {
position: absolute;
width: 60px;
height: 60px;
float: left;
}
.first {
background-color: #3f3;
left: 0;
}
.second {
background-color: #33f;
left: 80px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<p><button>Run</button></p>
<div class="first"></div>
<div class="second"></div>
<script>
function fun1(){
    alert("fun1");
}
function fun2(){
    alert("fun2");
}
$( "button" ).click(function() {
    $(":root").delay(3000).queue(function(){
        fun1();
        $(this).dequeue()
    });
    $(":root").delay(5000).queue(function(){
        fun2();
        $(this).dequeue()
    });
    // $(":root").delay(3000, 'q').queue('q', function(){
    //     fun1();
    //     $("div.second").delay(5000, 'q').queue('q',function(){
    //     fun2();
    //     }).dequeue('q');
    // }).dequeue('q');

});
$(document).ready(function(){
    // alert("OK");
    $(":root").delay(3000).queue(function(){
        fun1();
        $(this).dequeue();
    });
    $(":root").delay(3000).queue(function(){
        fun2();
        $(this).dequeue();
    });
    // alert("end");
});
</script>
</body>
</html

参考资料:
http://api.jquery.com/queue/#queue-queueName-callback-next-
http://api.jquery.com/jQuery.queue/
http://blog.project-sierra.de/archives/1559

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值