(Turn) How to realize the function of sleep in JS

1. $.delay() method of jquery

  Set a delay to defer execution of later items in the queue. This method cannot replace JS's native setTimeout.

  The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

  Example: Delay 800ms between .slideUp() and .fadeIn().

  HTML code:

  <div id="foo /">

  jQuery code:

  $('#foo').slideUp(300).delay(800).fadeIn(400);

  2. Consume cpu by looping

  function sleep(n) {

  var start = new Date().getTime();

  while(true) if(new Date().getTime()-start > n) break;

  }

  3. 用setTimeout。

  Suppose there are three steps, and there is a pause between steps; the following methods can be used:

  function firstStep() {

  //do something

  setTimeout("secondStep()", 1000);

  }

  function secondStep() {

  //do something

  setTimeout("thirdStep()", 1000);

  }

  function thirdStep() {

  //do something

  }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326966317&siteId=291194637