how to make a sleep in javascript?

后端 未结 9 1975
半阙折子戏
半阙折子戏 2020-12-20 23:00

Does anyone know how can I make a sleep in javascript before next line been read by the system?

example:

    1 var chkResult = Validation();
    2 /         


        
9条回答
  •  囚心锁ツ
    2020-12-20 23:38

    May I suggest this as a generic solution:

      function sleep (ms, args, obj) {
        /* Called at the top of a function to invoke a delay in processing that
           function
    
           Returns true if the function should be executed, and false if the sleep
           timer is activated. 
    
           At the end of the sleep tiemout, the calling function is re-called by
           calling it with "apply (obj, args || [])".
        */
    
        var caller = sleep.caller;
        if (caller.sleepTimer) { 
          /* if invoked from timeout function, delete timer and return false */
          delete caller.sleepTimer;
          return true;
        }
    
        /* Create timer and re-call caller at expiry */
        caller.sleepTimer = window.setTimeout (function () {
          caller.apply (obj || null, args || []);
        },ms);
    
        return false;
      }    
    

    Examples of use:

    function delayed () {
      if (!sleep (5000)) return;  
    
      document.body.innerHTML += "

    delayed processing

    "; } function delayed_args (a, b) { if (!sleep (10000, arguments)) return; document.body.innerHTML += "

    args : (" + a + ", " + b + ")

    "; } function delayed_method_args (a,b) { if (!sleep (20000, arguments, this)) return; document.body.innerHTML += "

    method_args " + this + " (" + a + ", " + b + ")

    "; }

    Tested on Opera and Firefox 3.0

提交回复
热议问题