使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM