Why is there no sleep function in javascript when there is setTimeout and setInterval?

Why is there no such function in javascript that sets a timeout for its continuation, saves the necessary state (region object and execution point), terminates the script and returns control to the browser? After the time-out, the browser will load the execution context and continue the script, and we will have a real blocking function without blocking the browser that would work even if the JS engine was single-threaded.

Why is there no such functionality in javascript? Why should we still slice our code into functions and set timeouts to the next step to achieve a sleep effect?

+5
source share
6 answers

I think that "dream" is what you do not want in your browser.

First of all, it may not be clear what should happen and how the browser should behave when you are really sleeping.

  • Is Full Script a Sleep Runtime? This is usually necessary because you only have one thread on which your code runs. So what happens if other events fumigate during sleep? they will be blocked, and as soon as execution continues, all blocked events will fire. This will cause strange behavior that you can imagine (for example, mouse click events that fire after a while, or maybe seconds, after the actual click). Or these events should have been ignored, which would lead to a loss of information.

  • ? , (, )? , , javascript- (), , .

. //, , , . (, XHR), . . :

  • ( - )
  • , ( , , ...)

... : , . , , , . , , , , , - .

, , Javascript, . , javascripts ;)

+5

javascript , , , , , gif , " " .

+4

, setTimeout yield ?

yield JavaScript?

, .

, Mozilla ?

+2

"sleep()" JavaScript , - .

+1

, yield Deferreds (, jquery).

-, . , javascript > 1.7. :

:

$$ = function (generator) {
    var d = $.Deferred();
    var iter;
    var recall = function() {
       try {var def = iter.send.apply(iter, arguments);} catch(e) {
          if (e instanceof StopIteration) {d.resolve(); return;}
          if (e instanceof ReturnValueException) {
              d.resolve(e.retval); return
          };
          throw e;
       };
       $.when(def).then(recall);      // close the loop !
    };
    return function(arguments) {
         iter = generator.apply(generator, arguments);
         var def = iter.next();        // init iterator
         $.when(def).then(recall);     // loop in all yields
         return d.promise();           // return a deferred
    }
}

ReturnValueException = function (r) {this.retval = r; return this; };
Return = function (retval) {throw new ReturnValueException(retval);};

, , jquery, $ JQuery acces ( ).

:

function Sleep(time) {
  var def = $.Deferred();
  setTimeout(function() {def.resolve();}, time);
  return def.promise();
}

( , ):

// Sample function that take 3 seconds to execute
fakeAjaxCall = $$(function () {
   yield (Sleep(3000));
   Return("AJAX OK");
});

:

function log(msg) {$('<div>'+msg+'</div>').appendTo($("#log")); }

demoFunction = $$(function (arg1, arg2) {
   var args = [].splice.call(arguments,0);
   log("Launched, arguments: " + args.join(", "));
   log("before sleep for 3secs...");
   yield (Sleep(3000));
   log("after sleep for 3secs.");

   log("before call of fake AjaxCall...");
   ajaxAnswer = yield (fakeAjaxCall());
   log("after call of fake AjaxCall, answer:" + ajaxAnswer);

   // You cannot use return, You'll have to use this special return
   // function to return a value
   log("returning 'OK'.");
   Return("OK");
   log("should not see this.");
});

, :

:

  • , , $$(myFunc)
  • $$ , . , .
  • 'Return' .
  • Javascript 1.7 ( firefox)
+1

, , , , . , Promises ECMAscript 7 ( JavaScript), :

// First we define our "sleep" function...
function sleep(milliseconds) {
  // Immediately return a promise that resolves after the
  // specified number of milliseconds.
  return new Promise(function(resolve, _) {
    setTimeout(resolve, milliseconds);
  });
}

// Now, we can use sleep inside functions declared as asynchronous
// in a way that looks like a synchronous sleep.
async function helloAfter(seconds) {
  console.log("Sleeping " + seconds + " seconds.");
  await sleep(seconds * 1000); // Note the use of await
  console.log("Hello, world!");
}

helloAfter(1);
console.log("Script finished executing.");

:

Sleeping 1 seconds.
Script finished executing.
Hello, world!

( Babel)

, , , , sleep . , , Promise, .

helloAfter async, . , , , helloAfter Promise . "Script ". ", !".

helloAfter async await . . await sleep(seconds * 1000); , helloAfter , , sleep, . , : - helloAfter. , helloAfter , "Hello, world!". .

async/await, ES7.

+1

All Articles