In class a couple months ago (the Angular Boot Camp I often teach), a student asked how to do something like Thread.sleep(n) in JavaScript. Of course there isn’t such a thing, at least in the main JS execution environments (browsers, Node). Rather there is the asynchronous equivalent of setTimeout().
But there is an equivalent, nearly as terse way to insert a delay in a promise chain. Here is a short (thought perhaps not optimally short) sleep equivalent. This is for use in an AngularJS app, with its $q promise implementation.
angular.module("whatever", [])
.factory("kcSleep", function($timeout) {
return function(ms) {
return function(value) {
return $timeout(function() {
return value;
}, ms);
};
};
});
// to use it:
somePromise
.then(kcSleep(1000))
.then(whatever);