javascript - 暂停/恢复在nodejs中执行的代码

标签 javascript node.js timer

所以我正在制作某种游戏,玩家可以在其中获得一些能力。玩家回合结束后,服务器应有 5 秒的超时时间,其中不执行任何代码,然后在该时间后结束回合。但是,如果客户端单击其中一项电源,服务器应停止 5 秒超时并再次开始执行。我该如何实现这个?

目前我正在使用,

await new Promise(r => setTimeout(r, 5000))

它会停止并等待超时结束,但是当客户端选择 powerUp 时如何停止超时?我们如何清除基于 Promise 的超时?

简而言之,我想做的是:

server side code

function doSomething(){
     if(playerHasPowerUps) await new Promise(r => setTimeout(r, 5000))
     //do other things
}

in client side in this period if the player clicks on a powerup, it informs the server about the event and the server is meant to stop the above timeout and do other things

最佳答案

我的解决方案是创建一个管理 Promise 和 Timeout 实例的类。

让我们将这个类命名为 Sleep,它在其构造函数中获取持续时间,并根据给定的持续时间安排超时,并创建一个 Promise 实例。

添加一个异步函数wait(),它返回promise实例,以便我们可以await

添加一个函数cancel(),它可以简单地解析 Promise 实例并清除超时。

<html>
	<body>
		<button onClick="cancelWait()">Cancel wait</button>
		<div id="text"></div>
	</body>

	<script lang="javascript">

		class Sleep {
		   constructor(duration) {
			  this.promise = new Promise((resolve) => {
				this.promiseResolve = resolve
				this.timeout = setTimeout(() => {
				  resolve()
				}, duration)
			  })
		   }
		   
		   async wait() {
			  return await this.promise
		   }
		   
		   cancel() {
			  clearTimeout(this.timeout)
			  this.promiseResolve()
		   }
		}

		//Usage
		let sleep
		
		const main = async () => {
			const text = document.getElementById("text")
			text.innerText = 'start'			
						
			sleep = new Sleep(3000)
			await sleep.wait()	

			text.innerText = 'finish'
		}
		
		const cancelWait = () => {
			sleep.cancel()
		}
		
		main()

	</script>

</html>

关于javascript - 暂停/恢复在nodejs中执行的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58636410/

相关文章:

javascript - 避免将特定模块与 Browserify 捆绑在一起

javascript - 在 Node 脚本末尾运行行?

javascript - 如何使用使用相同查询参数的 super 代理发送请求

java - 使用Timer调用AsyncTask类

Java 定时器与 Linux Cronjob

javascript - 获取表单中相对于按钮的输入值

javascript - 将带有毫秒的unix时间戳转换为postgres可读的timestamptz

javascript - Node.js : Load . js 和 .css 文件包含在没有 Express/frameworks 的 HTML 文件中

python:在shell上显示耗时

php - $_GET、$_SESSION 和 XMLHttpRequest 的问题