PRogram to demonstrate asynch/await, promise call back in javascript
5. b. Simulate a periodic stock price change and display on the console. Hints: (i) Create a method which returns a random number - use Math.random, floor and other methods to return a rounded value. (ii) Invoke the method for every three seconds and stop , use Asynchronous Programming, Callbacks, Promises, Async and Await
without graphics
****************
function getRandomStockPrice() {
return (Math.random() * (200 - 100) + 100).toFixed(2); // Generates a price between 100 and 200
}
async function simulateStockPriceUpdates(interval, updatesCount) {
console.log("Starting stock price simulation...");
for (let i = 0; i < updatesCount; i++) {
await new Promise(resolve => setTimeout(resolve, interval));
console.log(`Stock Price Update ${i + 1}: $${getRandomStockPrice()}`);
}
console.log("Simulation ended.");
}
simulateStockPriceUpdates(3000, 5); // Run every 3 seconds for 5 updates
OUTPUT:
C:\Program Files\nodejs\node.exe d:\1.js
Starting stock price simulation...
1.js:6
Stock Price Update 1: $177.16
1.js:10
Stock Price Update 2: $187.63
1.js:10
Stock Price Update 3: $195.75
1.js:10
Stock Price Update 4: $122.81
1.js:10
Stock Price Update 5: $179.44
1.js:10
Simulation ended.
Comments
Post a Comment