Topic Description

Although JavaScript has a built-in method called setTimeout to control pausing and resuming the program, it is somewhat cumbersome to use. Please design a more streamlined mechanism, similar to the sleep function in other languages like Java and Python, while maintaining the asynchronous nature of JavaScript.

// 可以這樣
console.log('Explain');
await sleep(3000);  // 停 3 秒
console.log('This');

// 或者
console.log('Explain');
sleep(3000).then(() => {
  console.log('This'); // Only logs after 3 seconds
});

Answer

function sleep(ms){
	return new Promise(resolve => {
		setTimeout(resolve,ms)
	})
}