Is there an easy way to pause a script in javascript? I am looking for javascript equivalent time.sleep(1)in Python. I do NOT want setTimeout(continueExecution, 10)or anything with getTime. It can be done?
time.sleep(1)
setTimeout(continueExecution, 10)
getTime
EDIT: It wasn’t that easy, but I think I can do it with setTimeout
setTimeout
JavaScript usually runs in a single thread using an event loop. That is why you cannot do "Thread.sleep". If you could freeze it all the rest for this period and believe that you do not want to do this. This is why almost everything in JavaScript works using non-blocking IO, and therefore the only way to slow down is to use setTimeout or setInterval.
setTimeout, :
: . javascript , WILL . . .
var delay = 5; // 5 second delay var now = new Date(); var desiredTime = new Date().setSeconds(now.getSeconds() + delay); while (now < desiredTime) { now = new Date(); // update the current time } // continue execution
jQuery 1.5+, (i
(function($) { $.wait = function(time) { return $.Deferred(function(dfd) { setTimeout(dfd.resolve, time); // use setTimeout internally. }).promise(); } }(jQuery));
:
$.wait(3000).then(function(){ .... });
3 . setTimeout , JavaScript.
: ( http://www.phpied.com/sleep-in-javascript/)
function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } }
script , . , , , - .
npm, sleep,
var sleep = require('sleep'); sleep.sleep(10) //sleep for 10 seconds
JavaScript, Node.js!
, , then-sleep npm,
var sleep = require('then-sleep'); // Sleep for 1 second and do something then. sleep(1000).then(...);
also if you use ES7, you can use the espm-sleep es7 package
ES7
You do something like this
// place you code in this function (async function main(){ //Do something console.log("something Done first ") // code execution will halt for period (ms) await sleep(3000) console.log("something Done 3 seconds later ") //Do something })() function sleep(period) { return new Promise(resolve => { setTimeout(() => { resolve(); }, period); }); }
if you use node 9.3 or higher you can use Atomics.wait()like this
Atomics.wait()
function msleep(n) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n); } function sleep(n) { msleep(n*1000); }
now you can call sleep()
sleep()