1.
- function sleep(n)
- {
- var start=new Date().getTime();
- while(true) if(new Date().getTime()-start> n) break;
- }
2. 利用setTimeout
- function doStuff()
- {
- //do some things
- setTimeout(continueExecution, 10000) //wait ten seconds before continuing
- }
- function continueExecution()
- {
- //finish doing things after the pause
- }
3.jquery中
- If you're using jQuery, someone actually created a "delay" plugin that's nothing more than a wrapper for setTimeout:
- // Delay Plugin for jQuery
- // - http://www.evanbot.com
- // - © 2008 Evan Byrne
- jQuery.fn.delay = function(time,func){
- this.each(function(){
- setTimeout(func,time);
- });
- return this;
- };
- You can then just use it in a row of function calls as expected:
- $('#warning')
- .addClass('highlight')
- .delay(1000)
- .removeClass('highlight');