// sleep time expects millisecondsfunction sleep (time) {return new Promise((resolve) => setTimeout(resolve, time));}
// Usage!sleep(500).then(() => {// Do something after the sleep!});
function doStuff(){// Do some thingssetTimeout(continueExecution, 10000) // Wait ten seconds before continuing}
function continueExecution(){// Finish doing things after the pause}
<html><body><div id="id1">DISPLAY</div>
<script>// JavaScript sleep by "therealdealsince1982"; copyrighted 2009// setIntervalvar i = 0;
function run() {// Pieces of codes to runif (i == 0){document.getElementById("id1").innerHTML= "<p>code segment " + i + " is ran</p>"; }if (i == 1){document.getElementById("id1").innerHTML= "<p>code segment " + i + " is ran</p>"; }if (i == 2){document.getElementById("id1").innerHTML= "<p>code segment " + i + " is ran</p>"; }if (i >2){document.getElementById("id1").innerHTML= "<p>code segment " + i + " is ran</p>"; }if (i == 5){document.getElementById("id1").innerHTML= "<p>all code segment finished running</p>"; clearInterval(t); } // End interval, stops runi++; // Segment of code finished running, next...}
run();t = setInterval("run()", 1000);
</script></body></html>
示例2:
<html><body><div id="id1">DISPLAY</div>
<script>// JavaScript sleep by "therealdealsince1982"; copyrighted 2009// setTimeoutvar i = 0;
function run() {// Pieces of codes to run, can use switch statementif (i == 0){document.getElementById("id1").innerHTML= "<p>code segment " + i + " ran</p>"; sleep(1000);}if (i == 1){document.getElementById("id1").innerHTML= "<p>code segment " + i + " ran</p>"; sleep(2000);}if (i == 2){document.getElementById("id1").innerHTML= "<p>code segment " + i + " ran</p>"; sleep(3000);}if (i == 3){document.getElementById("id1").innerHTML= "<p>code segment " + i + " ran</p>";} //stops automaticallyi++;}
function sleep(dur) {t=setTimeout("run()", dur);} // Starts flow control again after 'dur'
run(); // Starts</script></body></html>
示例3:
<html><body><div id="id1">DISPLAY</div>
<script>// JavaScript sleep by "therealdealsince1982"; copyrighted 2009// setTimeoutvar i = 0;
function flow() {run(i);i++; // Code segment finished running, increment i; can put elsewheresleep(1000);if (i == 5) {clearTimeout(t);} // Stops flow, must be after sleep()}
function run(segment) {// Pieces of codes to run, can use switch statementif (segment == 0){document.getElementById("id1").innerHTML= "<p>code segment " + segment + " is ran</p>"; }if (segment == 1){document.getElementById("id1").innerHTML= "<p>code segment " + segment + " is ran</p>"; }if (segment == 2){document.getElementById("id1").innerHTML= "<p>code segment " + segment + " is ran</p>"; }if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }}
function sleep(dur) {t=setTimeout("flow()", dur);} // Starts flow control again after 'dur'
flow(); // Starts flow</script></body></html>
例4:
<html><body><div id="id1">DISPLAY</div>
<script>// JavaScript sleep by "therealdealsince1982"; copyrighted 2009// setTimeout, switchvar i = 0;
function flow() {switch(i){case 0:run(i);sleep(1000);break;case 1:run(i);sleep(2000);break;case 5:run(i);clearTimeout(t); // Stops flowbreak;default:run(i);sleep(3000);break;}}
function run(segment) {// Pieces of codes to run, can use switch statementif (segment == 0){document.getElementById("id1").innerHTML= "<p>code segment " + segment + " is ran</p>"; }if (segment == 1){document.getElementById("id1").innerHTML= "<p>code segment " + segment + " is ran</p>"; }if (segment == 2){document.getElementById("id1").innerHTML= "<p>code segment " + segment + " is ran</p>"; }if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment " + segment + " is ran</p>"; }i++; // Current segment of code finished running, next...}
function sleep(dur) {t=setTimeout("flow()", dur);} // Starts flow control again after 'dur'
flow(); // Starts flow control for first time...</script></body></html>
function itemHandler(item){alert(item);}
var itemSet = ['a','b','c'];
// Each call to itemHandler will execute// 1 second apartfor(var i=0; i<itemSet.length; i++){var secondsUntilExecution = i;itemHandler.delay(secondsUntilExecution, item)}
alert('start');var a = 'foo';// Lots of codesetTimeout(function(){ // Beginning of code that should run AFTER the timeoutalert(a);// Lots more code}, 5000); // Put the timeout here
// A module to do that //dual-license: MIT or WTF [you can use it anyhow and leave my nickname in a comment if you want to]var _ = (function(){var queue = [];var play = function(){var go = queue.shift();if(go) {if(go.a) {go.f();play();}else{setTimeout(play, go.t);}}}return {go:function(f){queue.push({a:1, f:f});},sleep:function(t){queue.push({a:0, t:t});},playback:play}})();
[自动播放也应该是可能的]
// Usage
_.go(function(){
// Your codeconsole.log('first');
});
_.sleep(5000);
_.go(function(){
// Your codeconsole.log('next');
});
// This triggers the simulation_.playback();
try{java.lang.Thread.sleep(timeInMilliseconds);}catch (e){/** This will happen if the sleep is woken up - you might want to check* if enough time has passed and sleep again if not - depending on how* important the sleep time is to you.*/}
/*** Netscape compatible WaitForDelay function.* You can use it as an alternative to Thread.Sleep() in any major programming language* that support it while JavaScript it self doesn't have any built-in function to do such a thing.* parameters:* (Number) delay in millisecond*/function nsWaitForDelay(delay) {/*** Just uncomment this code if you're building an extension for Firefox.* Since Firefox 3, we'll have to ask for user permission to execute XPCOM objects.*/netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
// Get the current thread.var thread = Components.classes["@mozilla.org/thread-manager;1"].getService(Components.interfaces.nsIThreadManager).currentThread;
// Create an inner property to be used later as a notifier.this.delayed = true;
/* Call JavaScript setTimeout function* to execute this.delayed = false* after it finishes.*/setTimeout("this.delayed = false;", delay);
/*** Keep looping until this.delayed = false*/while (this.delayed) {/*** This code will not freeze your browser as it's documented in here:* https://developer.mozilla.org/en/Code_snippets/Threads#Waiting_for_a_background_task_to_complete*/thread.processNextEvent(true);}}
function SomeObject() {this.SomeProperty = "xxx";return this;}SomeObject.prototype.SomeMethod = function () {this.DoSomething1(arg1);sleep(500);this.DoSomething2(arg1);}
几乎可以翻译成:
function SomeObject() {this.SomeProperty = "xxx";return this;}SomeObject.prototype.SomeMethod = function (arg1) {var self = this;self.DoSomething1(arg1);setTimeout(function () {self.DoSomething2(arg1);}, 500);}
// Basic sleep function based on ms.// DO NOT USE ON PUBLIC FACING WEBSITES.function sleep(ms) {var unixtime_ms = new Date().getTime();while(new Date().getTime() < unixtime_ms + ms) {}}
var Fiber = require('fibers');
function sleep(ms) {var fiber = Fiber.current;setTimeout(function() {fiber.run();}, ms);Fiber.yield();}
Fiber(function() {console.log('wait... ' + new Date);sleep(1000);console.log('ok... ' + new Date);}).run();console.log('back in main');
function sleepFor(sleepDuration){var now = new Date().getTime();while(new Date().getTime() < now + sleepDuration){ /* Do nothing */ }}
使用示例:
function sleepFor(sleepDuration){var now = new Date().getTime();while(new Date().getTime() < now + sleepDuration){/* Do nothing */}}
function sleepThenAct(){sleepFor(2000);console.log("Hello, JavaScript sleep!");}
sleepThenAct()
// execute code consecutively with delays (blocking/non-blocking internally)function timed_functions(){this.myfuncs = [];this.myfuncs_delays = []; // mirrors keys of myfuncs -- values stored are custom delays, or -1 for use defaultthis.myfuncs_count = 0; // increment by 1 whenever we add a functionthis.myfuncs_prev = -1; // previous index in arraythis.myfuncs_cur = 0; // current index in arraythis.myfuncs_next = 0; // next index in arraythis.delay_cur = 0; // current delay in msthis.delay_default = 0; // default delay in msthis.loop = false; // will this object continue to execute when at end of myfuncs array?this.finished = false; // are we there yet?this.blocking = true; // wait till code completes before firing timer?this.destroy = false; // <advanced> destroy self when finished
this.next_cycle = function() {var that = this;var mytimer = this.delay_default;
if(this.myfuncs_cur > -1)if(this.myfuncs_delays[this.myfuncs_cur] > -1)mytimer = this.myfuncs_delays[this.myfuncs_cur];
console.log("fnc:" + this.myfuncs_cur);console.log("timer:" + mytimer);console.log("custom delay:" + this.myfuncs_delays[this.myfuncs_cur]);setTimeout(function() {// Time is up! Next cycle...that.cycle();
}, mytimer);}
this.cycle = function() {
// Now check how far we are along our queue.. is this the last function?if(this.myfuncs_next + 1 > this.myfuncs_count){if(this.loop){console.log('looping..');this.myfuncs_next = 0;}elsethis.finished = true;}
// First check if object isn't finishedif(this.finished)return false;
// HANDLE NON BLOCKING //if(this.blocking != true) // Blocking disabled{console.log("NOT BLOCKING");this.next_cycle();}
// Set prev = current, and current to next, and next to new nextthis.myfuncs_prev = this.myfuncs_cur;this.myfuncs_cur = this.myfuncs_next;this.myfuncs_next++;
// Execute current slotthis.myfuncs[this.myfuncs_cur]();
// HANDLE BLOCKINGif(this.blocking == true) // Blocking enabled{console.log("BLOCKING");this.next_cycle();}
return true;};
// Addersthis.add = {that:this,
fnc: function(aFunction) {// Add to the function arrayvar cur_key = this.that.myfuncs_count++;this.that.myfuncs[cur_key] = aFunction;// Add to the delay reference arraythis.that.myfuncs_delays[cur_key] = -1;}}; // end::this.add
// settersthis.set = {that:this,
delay: function(ms) {var cur_key = this.that.myfuncs_count - 1;// This will handle the custom delay array this.that.myfunc_delays// Add a custom delay to your function container
console.log("setting custom delay. key: "+ cur_key + " msecs: " + ms);if(cur_key > -1){this.that.myfuncs_delays[cur_key] = ms;}// So now we create an entry on the delay variable},
delay_cur: function(ms) { this.that.delay_cur = ms; },delay_default: function(ms) { this.that.delay_default = ms; },loop_on: function() { this.that.loop = true; },loop_off: function() { this.that.loop = false; },blocking_on: function() { this.that.blocking = true; },blocking_off: function() { this.that.blocking = false; },
finished: function(aBool) { this.that.finished = true; }}; // end::this.set
// Settersthis.get = {that:this,
delay_default: function() { return this.that.delay_default; },delay_cur: function() { return this.that.delay_cur; }}; // end::this.get
} // end:::function timed_functions()
并像这样使用它:
// // // BEGIN :: TEST // // //
// Initializevar fncTimer = new timed_functions;
// Set some defaultsfncTimer.set.delay_default(1000);fncTimer.set.blocking_on();// fncTimer.set.loop_on();// fncTimer.set.loop_off();
// BEGIN :: ADD FUNCTIONS (they will fire off in order)fncTimer.add.fnc(function() {console.log('plan a (2 secs)');});fncTimer.set.delay(2000); // Set a custom delay for previously added function
fncTimer.add.fnc(function() {console.log('hello world (delay 3 seconds)');});fncTimer.set.delay(3000);
fncTimer.add.fnc(function() {console.log('wait 4 seconds...');});fncTimer.set.delay(4000);
fncTimer.add.fnc(function() {console.log('wait 2 seconds');});fncTimer.set.delay(2000);
fncTimer.add.fnc(function() {console.log('finished.');});// END :: ADD FUNCTIONS
// NOW RUNfncTimer.cycle(); // Begin execution
// // // END :: TEST // // //
// This is based on the latest ES6 drafts.// JavaScript 1.7+ (SpiderMonkey/Firefox 2+) syntax is slightly different
// Run code you want to sleep here (omit star if using JavaScript 1.7)function* main(){for (var i = 0; i < 10; i++) {// To sleep for 10 milliseconds 10 times in a rowyield 10;}
yield 5;console.log('I just slept 5 milliseconds!');}
// Resume the given generator after ms millisecondsfunction resume(ms, generator){setTimeout(function(){// Omit .value if using JavaScript 1.7var nextSleep = generator.next().value;resume(nextSleep, generator);}, ms);}
// Initialize a generator and get first sleep for the recursive functionvargenerator = main(),firstSleep = generator.next().value;
// Initialize recursive resume functionresume(firstSleep, generator);
createWaitRunner = function (completionCallback) {var callback = completionCallback;var completionRecord = [];var elements = 0;
function maybeFinish() {var done = completionRecord.every(function (element) {return element === true});
if (done)callback();}
return {getNotifier: function (func) {func = func || function (){};
var index = elements++;completionRecord[index] = false;
return function () {func.applyTo(arguments);completionRecord[index] = true;maybeFinish();}}}};
// Provides a context for running asynchronous methods synchronously// The context just provides a way of sharing bits of state// Use 'run' to execute the methods. These should be methods that take a callback and optionally the context as arguments// Note the callback is provided first, so you have the option of just partially applying your function to the arguments you want// instead of having to wrap even simple functions in another function
// When adding steps you can supply either just a function or a variable name and a function// If you supply a variable name then the output of the function (which should be passed into the callback) will be written to the contextcreateSynchronisedRunner = function (doneFunction) {var context = {};
var currentPosition = 0;var steps = [];
// This is the loop. It is triggered again when each method finishesvar runNext = function () {var step = steps[currentPosition];step.func.call(null,function (output) {step.outputHandler(output);currentPosition++;
if (currentPosition === steps.length)return;
runNext();}, context);};
var api = {};
api.addStep = function (firstArg, secondArg) {var assignOutput;var func;
// Overloadsif (secondArg === undefined) {assignOutput = function () {};func = firstArg;}else {var propertyName = firstArg;assignOutput = function (output) {context[propertyName] = output;};func = secondArg;}
steps.push({func: func,outputHandler: assignOutput});};
api.run = function (completedAllCallback) {completedAllCallback = completedAllCallback || function(){};
var lastStep = steps[steps.length - 1];var currentHandler = lastStep.outputHandler;lastStep.outputHandler = function (output) {currentHandler(output);completedAllCallback(context);doneFunction();};
runNext();};
// This is to support more flexible use where you use a done function in a different scope to initialisation// For example, the done of a test but create in a beforeEachapi.setDoneCallback = function (done) {doneFunction = done;};
return api;};
function sleep(n){var request = new XMLHttpRequest();request.open('GET', '/sleep.php?n=' + n, false); // `false` makes the request synchronousrequest.send(null);}
文件sleep.php的内容:
<?php sleep($_GET['n']);
现在调用它:
sleep(5);
使用现有的服务器实现
如果您没有自己的应用程序服务器(对于上述PHP脚本),您可以使用一些在线服务。例如:
function sleep(n) {var request = new XMLHttpRequest();request.open('GET', 'http://httpstat.us/200?sleep=' + n, false);request.send(null);};
sleep(1000);console.log("one second delay completed.");
// Works only inside a web worker
function sleep(milliseconds) {var req = new XMLHttpRequest();req.open("GET", "http://192.0.2.0/", false);req.timeout = milliseconds;try {req.send();} catch (ex) {
}}
console.log('Sleeping for 1 second...');sleep(1000);console.log('Slept!');
console.log('Sleeping for 5 seconds...')sleep(5000);console.log('Slept!');
function coroutine1() {this.a = 100;console.log('coroutine1-1:start');return sleepFor(3000).yield; // Sleep for 3 seconds hereconsole.log('coroutine1-2:complete');this.a++;}
var c1 = new coroutine1();
function coroutine2(c) {/* Some code here */this.a = 1;console.log('coroutine2-1:' + this.a++);return sleepFor(500).yield;
/* Next */console.log('coroutine2-2:' + this.a++);console.log('coroutine2-2:waitFor c.a>100:' + c.a);return waitFor(function() {return c.a>100;}).yield;
/* The rest of the code */console.log('coroutine2-3:' + this.a++);}
var milliseconds;var pretime;var stage;
function step(time){switch(stage){case 0://Code before the pause
pretime=time;milliseconds=XXX;stage=1;break;case 1://Code that is looped through while paused
if(time-pretime >= milliseconds){//Code after the pause
pretime=time;milliseconds=XXX;stage=2;}break;case 2://Code that is looped through while paused
if(time-pretime >= milliseconds){//Code after the pause
pretime=time;milliseconds=XXX;stage=3;}break;case 3://Etc...}
Window.requestAnimationFrame(step)}
step();
var h = a();h.next().value.r = h; // That's how you run it. It is the best I came up with
// Sleep without breaking the stack!!!function *a(){var obj = {};
console.log("going to sleep....2s")
setTimeout(function(){obj.r.next();}, 2000)yield obj;
console.log("woke up");console.log("going to sleep no 2....2s")setTimeout(function(){obj.r.next();}, 2000)yield obj;
console.log("woke up");console.log("going to sleep no 3....2s")
setTimeout(function(){obj.r.next();}, 2000)yield obj;
console.log("done");}
function myFunc() {
console.log ("Do some things");
setTimeout(function doTheRest(){console.log ("Do more things...");}, 5000);
// Returns undefined.};
myFunc();
一个返回Promise的例子(注意它改变了你的函数用法):
function myFunc(someString) {
return new Promise(function(resolve, reject) {
var result = [someString];result.push("Do some things");
setTimeout(function(){result.push("Do more things...");resolve(result.join("\n"));}, 5000);});};
// But notice that this approach affect to the function usage...// (It returns a promise, not actual data):myFunc("Hello!!").then(function(data){console.log(data);}).catch(function(err){console.error(err);});
var reloadAfter = 10; //secondsvar intervalId = setTimeout(function() {//code you want to execute after the time waiting}, reloadAfter * 1000); // 60000 = 60 sec = 1 min
var get_hyper = function(node, maxcount, only_relation) {if (node.offsetParent === null) {// node is hiddensetTimeout(function () { get_hyper(node, maxcount, only_relation)},1000);return;};
// Enter the code here that waits for that node becoming visible// before getting executed.
};
let ms = 10000;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
运行了几个10秒的计时器基准测试。
使用setTimeout,我得到的错误高达7000微秒(7毫秒)。
使用原子,我的错误似乎保持在600微秒(0.6毫秒)以下
2020年更新:总结
function sleep(millis){ // Need help of a server-side pagelet netMillis = Math.max(millis-5, 0); // Assuming 5 ms overheadlet xhr = new XMLHttpRequest();xhr.open('GET', '/sleep.jsp?millis=' + netMillis + '&rand=' + Math.random(), false);try{xhr.send();}catch(e){}}
function sleepAsync(millis){ // Use only in async functionlet netMillis = Math.max(millis-1, 0); // Assuming 1 ms overheadreturn new Promise((resolve) => {setTimeout(resolve, netMillis);});}function sleepSync(millis){ // Use only in worker thread, currently Chrome-onlyAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);}
function sleepTest(){console.time('sleep');sleep(1000);console.timeEnd('sleep');}
async function sleepAsyncTest(){console.time('sleepAsync');await sleepAsync(1000);console.timeEnd('sleepAsync');}
function sleepSyncTest(){let source = `${sleepSync.toString()}console.time('sleepSync');sleepSync(1000);console.timeEnd('sleepSync');`;let src = 'data:text/javascript,' + encodeURIComponent(source);console.log(src);var worker = new Worker(src);}
for (let e = performance.now() + 2000; performance.now() < e; ) {}
在这里使用,setTimeout回调至少在两秒钟后才会被调用,即使它几乎立即进入事件队列:
setTimeout(function() {console.log("timeout finished");}, 0);
for (let e = performance.now() + 2000; performance.now() < e; ) {}console.log("haha wait for me first");
// Conceptualizing, using an interpolation example to illustrate// how to think about "await" and "async" functions`code${await then-restart-point}more-code${await then-restart-point}`
const wait = t => new Promise(s => setTimeout(s, t));// Usageasync function demo() {// Count downlet i = 6;while (i--) {await wait(1000);console.log(i);}// Sum of numbers 0 to 5 using by delay of 1 secondconst sum = await [...Array(6).keys()].reduce(async (a, b) => {a = await a;await wait(1000);const result = a + b;console.log(`${a} + ${b} = ${result}`);return result;}, Promise.resolve(0));console.log("sum", sum);}demo();
var timeout;
function sleep(delay) {if(timeout) {clearTimeout(timeout);}timeout = setTimeout(function() {myFunction();}, delay);}
console.log("sleep for 1 second");sleep(1000);
function myFunction() {console.log("slept for 1 second!");}
const sleep = (seconds) => {const waitUntil = new Date().getTime() + seconds * 1000while(new Date().getTime() < waitUntil) {// do nothing}}
你可以像这样使用sleep()方法:
const main = () => {const a = 1 + 3
// Sleep 3 seconds before the next actionsleep(3)const b = a + 4
// Sleep 4 seconds before the next actionsleep(4)const c = b + 5}
main()
// define sleep using setTimeoutconst sleep = (seconds, callback) => setTimeout(() => callback(), seconds * 1000)
const main = () => {const a = 1 + 3let b = undefinedlet c = undefined
// Sleep 3 seconds before the next actionsleep(3, () => {b = a + 4
// Sleep 4 seconds before the next actionsleep(4, () => {c = b + 5})})}
main()
const sleep = (seconds) => new Promise((resolve => setTimeout(() => resolve(), seconds * 1000)))
const main = () => {const a = 1 + 3let b = undefinedlet c = undefined
// Sleep 3 seconds before the next actionreturn sleep(3).then(() => {b = a + 4
// Sleep 4 seconds before the next actionreturn sleep(4)}).then(() => {c = b + 5})}
main()
const sleep = (seconds) => new Promise((resolve => setTimeout(() => resolve(), seconds * 1000)))
const main = async () => {const a = 1 + 3
// Sleep 3 seconds before the next actionawait sleep(3)const b = a + 4
// Sleep 4 seconds before the next actionawait sleep(4)const c = b + 5}
main()
const sleep = time => new Promise(res => setTimeout(res, time, "done sleeping"));
// using native promisessleep(2000).then(msg => console.log(msg));
异步/等待示例:
const sleep = time => new Promise(res => setTimeout(res, time, "done sleeping"));
// using async/await in top level(async function(){const msg = await sleep(2000);console.log(msg);})();