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