<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title> javascript sleep class -- demo </title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta http-equiv="content-language" content="zh-cn" /> <meta name="generator" content="editplus" /> <meta name="author" content="peter" /> <script type="text/javascript">
/** * javascript sleep class * @create : 2007-11-30 * * @Description : * 利用setTimeout函数,模拟 Sleep 功能 * * @author xiaosa | [url]http://0xs.cn[/url] */ //创建Sleep类 function SleepClass(){ this.todoList = []; this.processing = false; } //将Task加入队列 SleepClass.prototype.addTask = function(toDo, interVal){ this.todoList.push({'todo':toDo, 'itv':interVal}); if(!this.processing) this.go(); } //顺序执行Task SleepClass.prototype.go = function(){ if(!this.todoList.length){ this.processing = false; clearTimeout(this.timmerHandle); delete this.timmerHandle; return; } this.processing = true; var me = this; this.timmerHandle = setTimeout(function(){ me.todoList[0].todo(); me.todoList.shift(); me.go(); }, this.todoList[0].itv); }
//快捷方式 function sleep (toDo, interval){ if(!window.oSleep) window.oSleep = new SleepClass(); window.oSleep.addTask(toDo, interval); }
//测试代码 var d1 = new Date(); var logTime = ""; sleep(function(){ logTime += 'Do job 1 , Time:' + (new Date()-d1) + '<br/>'; }, 1000); sleep(function(){ logTime += 'Do job 2 , Time:' + (new Date()-d1) + '<br/>'; }, 2000); sleep(function(){ $('loading').innerHTML = 'sleep test ok! <hr size="1"/>' + logTime; }, 500);
var $ = function(el){ return document.getElementById(el);} window.onload = function(){ $('loading').innerHTML = 'loading.... please wait !'; }
</script> <style> *,html, body { font-size: 12px; } </style> </head> <body> <span id="loading"></span> </body> </html>