जेनरेटर फंक्शंस जब किसी फंक्शन से बाहर निकलता है और बाद में फिर से शुरू होता है तो बीच में कोड के निष्पादन की अनुमति देता है। तो, जनरेटर का उपयोग एक कोड में प्रवाह नियंत्रण को प्रबंधित करने के लिए किया जा सकता है। अतुल्यकालिक संचालन को आसानी से रद्द करें क्योंकि निष्पादन को कभी भी रोका जा सकता है।
यहाँ वाक्य रचना है; "फ़ंक्शन" कीवर्ड के बाद तारांकन जोड़ना न भूलें। आप निम्न में से किसी का उपयोग करके तारांकन जोड़ सकते हैं -
function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {} उदाहरण
आइए देखें कि जेनरेटर फ़ंक्शन का उपयोग कैसे करें
लाइव डेमो
<html>
<body>
<script>
function* display() {
var num = 1;
while (num < 5)
yield num++;
}
var myGenerator = display();
document.write(myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
</script>
</body>
</html>