Synchronous delay in code execution

前端 未结 10 1191
长情又很酷
长情又很酷 2020-12-03 02:29

I have a code which needs to be executed after some delay say 5000 ms.Currently I am using setTimeout but it is asynchronous and i want the execution to wait for its return.

10条回答
  •  误落风尘
    2020-12-03 03:12

    I have made a simple synchronous timeout function. It works in two different ways, callback and non-callback.

    function:

    function wait(ms, cb) {
      var waitDateOne = new Date();
      while ((new Date()) - waitDateOne <= ms) {
        //Nothing
      }
      if (cb) {
        eval(cb);
      }
    }
    

    callback example:

    wait(5000,"doSomething();");
    

    non-callback example:

    console.log("Instant!");
    wait(5000);
    console.log("5 second delay");
    

提交回复
热议问题