jsÖÐÔõÑùsleepÒ»Ãë
javascript ÖÐµÄ sleep ÒªÁ죺1. settimeout()£ºÑÓ³ÙÖ´Ðк¯Êý£¬ÈõµãÊÇÑÓ³Ùʱ¼ä½û¾øÈ·£»2. promise£º½¨ÉèÒì²½Íê³ÉµÄ promise£¬ÓŵãÊÇÑÓ³Ùʱ¼ä׼ȷ£¬¿É×éºÏÆäËûÒì²½²Ù×÷£»3. async/await£º±àд¿´ÆðÀ´Í¬²½µÄÒì²½´úÂ룬ÓŵãÊǿɶÁÐԸߣ¬ÈõµãÊÇÖ»ÄÜÔÚ´øÓÐ async Òªº¦×ֵĺ¯ÊýÖÐʹÓá£
JavaScript ÖÐÔõÑù Sleep Ò»Ãë
ÔÚ JavaScript ÖУ¬Ã»ÓÐÄÚÖÃµÄ sleep º¯Êý¡£È»¶ø£¬Óм¸ÖÖÒªÁì¿ÉÒÔʵÏÖÀàËƵÄÐÐΪ£º
setTimeout()
setTimeout() º¯ÊýÔÊÐíÄúÍýÏëÔÚ¸ø¶¨µÄÑÓ³ÙºóÖ´Ðк¯Êý¡£Òª Sleep Ò»Ã룬¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
setTimeout(() => { // ÔÚÕâÀïÖ´ÐÐ Sleep ºóµÄ´úÂë }, 1000);
µÇ¼ºó¸´ÖÆ
Óŵ㣺
¼òÆÓÒ×Óá£
Èõµã£º
ÑÓ³Ùʱ¼ä½û¾øÈ·£¬¿ÉÄܱ£´æÎó²î¡£
Promise
Promise ¿ÉÒÔÓÃÀ´ÌåÏÖÒì²½²Ù×÷µÄÍê³É¡£Òª Sleep Ò»Ã룬¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
const sleepPromise = new Promise((resolve) => { setTimeout(() => { resolve(); }, 1000); }); sleepPromise.then(() => { // ÔÚÕâÀïÖ´ÐÐ Sleep ºóµÄ´úÂë });
µÇ¼ºó¸´ÖÆ
Óŵ㣺
ÑÓ³Ùʱ¼ä¸ü׼ȷ¡£
¿ÉÒÔÇáËÉ×éºÏÆäËûÒì²½²Ù×÷¡£
Èõµã£º
Óï·¨ÉÔÏÔÖØ´ó¡£
async/await
async/await Óï·¨ÔÊÐíÄú±àд¿´ÆðÀ´Í¬²½µÄÒì²½´úÂë¡£Òª Sleep Ò»Ã룬¿ÉÒÔʹÓÃÒÔÏ´úÂ룺
async function sleep() { await new Promise((resolve) => { setTimeout(() => { resolve(); }, 1000); }); } sleep().then(() => { // ÔÚÕâÀïÖ´ÐÐ Sleep ºóµÄ´úÂë });
µÇ¼ºó¸´ÖÆ
Óŵ㣺
´úÂë¿É¶ÁÐԸߣ¬¿´ÆðÀ´Ïñͬ²½´úÂë¡£
Èõµã£º
Ö»ÄÜÔÚ´øÓÐ async Òªº¦×ֵĺ¯ÊýÖÐʹÓá£
ÒÔÉϾÍÊÇjsÖÐÔõÑùsleepÒ»ÃëµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡