node thread.sleep實現(xiàn)示例
最近在寫一些奇怪的東西的時候,發(fā)現(xiàn)大佬們用go或者其他語言實現(xiàn)的并發(fā)任務用了thread.sleep讓主進程暫停。
回頭一想,媽個雞我要復制粘貼到node一直循環(huán)不合適啊,我也需要暫停來著!
怎么辦??
抓了腦袋一會去npm上找了下相關的包,發(fā)現(xiàn)有個叫thread-sleep的包,下載量還挺高。
抱著好奇心去看了下源碼,又發(fā)現(xiàn)源碼相當之騷氣
'use strict'; var childProcess = require('child_process'); var nodeBin = process.argv[0]; module.exports = sleep; function sleep(milliseconds) { var start = Date.now(); if (milliseconds !== Math.floor(milliseconds)) { throw new TypeError('sleep only accepts an integer number of milliseconds'); } else if (milliseconds < 0) { throw new RangeError('sleep only accepts a positive number of milliseconds'); } else if (milliseconds !== (milliseconds | 0)) { throw new RangeError('sleep duration out of range') } milliseconds = milliseconds | 0; var shouldEnd = start + milliseconds; try { childProcess.execFileSync(nodeBin, [ '-e', 'setTimeout(function() {}, ' + shouldEnd + ' - Date.now());' ], { timeout: milliseconds, }); } catch (ex) { if (ex.code !== 'ETIMEDOUT') { throw ex; } } var end = Date.now(); return end - start; }
黑人問號???
這是什么奇怪的實現(xiàn)。
翻閱node文檔發(fā)現(xiàn)
Synchronous Process Creation#
The child_process.spawnSync(),
child_process.execSync(), and child_process.execFileSync() methods are synchronous and WILL block the Node.js event loop,
pausing execution of any additional code until the spawned process exits.Blocking calls like these are mostly useful for simplifying general-purpose scripting tasks and for simplifying the loading/processing of application configuration at startup.
???
以上三種同步方法會阻塞nodejs的事件循環(huán),除非創(chuàng)建的子進程執(zhí)行完了,才會繼續(xù)執(zhí)行下面的代碼。
thread-sleep包的作者正是利用這一特性實現(xiàn)了sleep功能。嘆為觀止
所以很多時候我們沒辦法解決現(xiàn)有問題的原因是對文檔不熟么??
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
阿里大于短信驗證碼node koa2的實現(xiàn)代碼(最新)
本文給大家分享一個最新版阿里大于短信驗證碼node koa2的實現(xiàn)代碼及注意事項,需要的朋友參考下吧2017-09-09nodejs連接mysql數(shù)據(jù)庫簡單封裝示例-mysql模塊
本篇文章主要介紹了nodejs連接mysql數(shù)據(jù)庫簡單封裝(mysql模塊),具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04nodejs文件實現(xiàn)打包成exe, 并設置開機自啟動的方法詳解(沒有黑窗口)
這篇文章主要介紹了nodejs文件實現(xiàn)打包成exe, 并設置開機自啟動的方法,結(jié)合實例形式分析了node.js使用pkg包實現(xiàn)生成exe可執(zhí)行文件的相關操作技巧,需要的朋友可以參考下2023-05-05node使用Mongoose類庫實現(xiàn)簡單的增刪改查
Mongoose是在nodejs環(huán)境中對MongoDB數(shù)據(jù)庫操作的封裝,這篇文章主要介紹了node使用Mongoose類庫實現(xiàn)簡單的增刪改查,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11