Home>Article>Web Front-end> Let’s talk about the sleep() method in javascript
Many programming languages havesleep()
,delay()
and other methods, which can make our program less anxious. Go to the next step, but delay and wait for a while. In software development, we often encounter functions that require such functions, such as waiting for a few minutes to check whether an event occurs. There is asetTimeout()
method in JavaScript to set a certain period of time to execute a task, but the writing method is very ugly and requires a callback function:
setTimeout(function(){ alert("Hello"); }, 3000);
JavaScript Promise API is a new one API, with the help of Promise, we can improve thesetTimeout
function. The following is to encapsulatesetTimeout()
into asleep()
function that returns Promise.
// https://zeit.co/blog/async-and-await function sleep (time) { return new Promise((resolve) => setTimeout(resolve, time)); } // 用法 sleep(500).then(() => { // 这里写sleep之后需要去做的事情 })
You will find that this way of writing is very elegant, much like delay and wait functions in other programming languages. The Promise API allows us to avoid passing in callback functions, and we also use the arrow function in ES6 in our implementation.
One issue that needs to be mentioned here is that thissleep()
continues to execute the "block" program during execution. It's not synchronous. If you want it to be executed synchronously without affecting subsequent code execution, we can use theasync/await
keyword.
(async function() { console.log('Do some thing, ' + new Date()); await sleep(3000); console.log('Do other things, ' + new Date()); })();
Execution result:
Do some thing, Mon Feb 23 2015 21:52:11 GMT+0800 (CST) Do other things, Mon Feb 23 2015 21:52:14 GMT+0800 (CST)
You will find that this time,sleep()
does not hinder the execution of the secondconsole
.
Butasync/await
is a syntax in ES7, which is still in the experimental stage. What should I do if I want to use thisasync/await
feature now? You can try traceur, a JavaScript precompiler from Google, which can compile higher versions of JavaScript into ES5 code. It has experimental support for async/await (you need to use –experimental to specify it).
Recommended tutorial: "javascript basic tutorial"
The above is the detailed content of Let’s talk about the sleep() method in javascript. For more information, please follow other related articles on the PHP Chinese website!