山田  千代

山田 千代

1658827080

JavaScript 休眠:如何讓你的函數休眠

有沒有更好的方法在 JavaScript 中創建睡眠?是的,自從 ES2015-2021 發布以來,JavaScript 有了很多改進,現在您可以按照自己的方式設計睡眠。

JavaScript 睡眠

要使您的函數在 JavaScript 中休眠,請使用async/awaitsetTimeout()函數的組合或作為單線:

await new Promise(res => setTimeout(res, 1000));

JavaScript 沒有內置的 sleep() 函數,但是由於引入了 Promise(以及ES2018中的async/await),我們可以以透明且精確的方式實現這些特性,讓你的函數休眠。

還有另一種在 JavaScript 中使用睡眠的方法。使用setTimeout()Promise的組合來故意延遲你的函數執行。

句法

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

論據

我們創建了一個以毫秒 為參數的sleep() 函數。sleep() 函數將創建一個新的 Promise,該 Promise 將在給定的毫秒內解析,以便在此之前暫停執行。解決後,它將開始繼續執行。

例子

// app.js

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

const list = [1, 2, 3, 4, 5]
const task = async () => {
  for (const item of list) {
    await sleep(1000);
    console.log('Yello, D\'oh');
  }
}

task();

在這個例子中,首先,我們定義了一個睡眠函數。然後,當我們需要休眠特定函數時,我們會調用 sleep() 函數。

在我們的代碼中,該特定函數是task()。 因此,我們將 在task()函數中使用sleep(  )函數來休眠。 

在這裡,我們使用了 async-await,因為 sleep() 將返回 promise。在函數之前,“異步”這個詞意味著一件簡單的事情:函數總是返回一個 Promise。2. 關鍵字“ await”讓 JavaScript 等待,直到 promise 完成並返回結果。

我們定義了一個可以幫助創建循環的數組列表。

task() 函數在 1 秒內記錄 Yello 和 D'oh 值。因此,函數進入休眠狀態一秒鐘,在 promise 解決後,它將在下一次記錄相同的字符串,然後再次休眠 1 秒鐘,以此類推。

輸出

Yello, D'oh
Yello, D'oh
Yello, D'oh
Yello, D'oh

上述語句將在延遲 1 秒後一一記錄。

如果您不想定義 sleep() 函數,則可以使用一行代碼來實現。

// app.js

const list = [1, 2, 3, 4]
const task = async () => {
  for (const item of list) {
    await new Promise(r => setTimeout(r, 2000));
    console.log('Yello, D\'oh');
  }
}

task();

在這裡,我們剛剛添加了以下代碼行。

// app.js

await new Promise(r => setTimeout(r, 2000));

請記住,這不會因為 JavaScript 的工作方式而暫停整個程序的執行(閱讀有關事件循環的更多信息),因為它可能在其他語言中發生。但相反,只有您的函數處於休眠狀態。

為了證明它不會暫停,讓我們在上面的代碼中添加一行簡單的代碼。

// app.js

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

const list = [1, 2, 3, 4]
const task = async () => {
  for (const item of list) {
    await new Promise(r => setTimeout(r, 2000));
    console.log('Yello, D\'oh');
  }
}

task();

console.log('Done!')

在這裡,我們添加了最後一行,它記錄了 Done!。task() 函數完成後,Javascript 引擎應該打印Done!。 

現在,讓我們運行上面的代碼並查看輸出。

Done!
Yello, D'oh
Yello, D'oh
Yello, D'oh
Yello, D'oh

你看到了問題,即使我們最後寫了,也會首先記錄完成。這就是在 JavaScript 中處理異步代碼的方式。這是因為在此處記錄語句是 JavaScript 中的異步操作。

當 JavaScript 解釋器遇到異步函數時,它不會等待請求完成。相反,它將繼續前進並記錄輸出“完成!” 到控制台,當請求在幾百毫秒後返回時,它將一一輸出語句。

這裡的問題是 JavaScript 是基於單線程事件的模型語言。因此,雖然在特定情況下,讓整個引擎等待幾秒鐘可能會很好,但這是一種糟糕的做法。但同樣,這取決於您要實現的目標並確保應用程序的性能。

JavaScript 中的睡眠注意事項

臭名昭著的睡眠或延遲是任何語言中的一種方法,一直在爭論。一些開發人員會說應該總是有信號或回調來觸發給定的功能;其他開發人員會爭辯說,有時任意延遲是可行的。

但我相信,對於每個人來說,一個規則永遠無法決定這個行業的任何事情。它基於您的需求和要求。

setTimeout() 方法不會阻止執行;它在超時設置後立即執行該方法的下一行,而不是在超時後執行。它無法完成與 sleep 方法相同的任務。

結論

JavaScript 睡眠是一個有爭議的概念。由於單線程語言的性質,我們無法像其他語言那樣實現完整的睡眠功能。但有時,在某些情況下,上述解決方案很有用。

JavaScript 中的時間問題可能會讓開發人員頭疼。但是,與它們打交道完全取決於您要達到的目標。

鏈接:https ://appdividend.com/2022/07/22/javascript-sleep/

#javascript

What is GEEK

Buddha Community

JavaScript 休眠:如何讓你的函數休眠

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Ajay Kapoor

1626321063

JS Development Company India | JavaScript Development Services

PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.

With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.

Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.

Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.

#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company

Santosh J

1622036598

JavaScript compound assignment operators

JavaScript is unarguablly one of the most common things you’ll learn when you start programming for the web. Here’s a small post on JavaScript compound assignment operators and how we use them.

The compound assignment operators consist of a binary operator and the simple assignment operator.

The binary operators, work with two operands. For example a+b where + is the operator and the a, b are operands. Simple assignment operator is used to assign values to a variable(s).

It’s quite common to modify values stored in variables. To make this process a little quicker, we use compound assignment operators.

They are:

  • +=
  • -+
  • *=
  • /=

You can also check my video tutorial compound assignment operators.

Let’s consider an example. Suppose price = 5 and we want to add ten more to it.

var price = 5;
price = price + 10;

We added ten to price. Look at the repetitive price variable. We could easily use a compound += to reduce this. We do this instead.

price += 5;

Awesome. Isn’t it? What’s the value of price now? Practice and comment below. If you don’t know how to practice check these lessons.

Lets bring down the price by 5 again and display it.
We use console.log command to display what is stored in the variable. It is very help for debugging.
Debugging let’s you find errors or bugs in your code. More on this later.

price -= 5;
console.log(price);

Lets multiply price and show it.

price *=5;
console.log(price);

and finally we will divide it.

price /=5;
console.log(price);

If you have any doubts, comment below.

#javascript #javascript compound assignment operators #javascript binary operators #javascript simple assignment operator #doers javascript