Hướng dẫn sleep function javascript

Home » Code

Show

    October 9, 2021

    Sử dụng sleep javascript – Với sự trợ giúp của Sleep (), ta có thể tạo một hàm để tạm dừng thực thi trong một khoảng thời gian cố định.

    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    async function demo() {
      console.log('Taking a break...');
      await sleep(2000);
      console.log('Two seconds later, showing sleep in a loop...');
    
      // Sleep in loop
      for (let i = 0; i < 5; i++) {
        if (i === 3)
          await sleep(2000);
        console.log(i);
      }
    }
    
    demo();

    I have searched/googled quite a few webpages on JavaScript sleep/wait... and there is no answer if you want JavaScript to "RUN, DELAY, RUN"... what most people got was either, "RUN, RUN(useless stuff), RUN" or "RUN, RUN + delayed RUN"...

    I thought: here is a solution that works... but you have to chop up your running codes...: Yes, I know, this is just an easier to read refactoring... still...

    Example 1:

    
    
    
    DISPLAY

    Example 2:

    
    
    
    DISPLAY

    Example 3:

    
    
    
    DISPLAY

    Example 4:

    
    
    
    DISPLAY