Created
August 5, 2021 20:28
-
-
Save pramodmg/1aebfbbcef75f3f6db7beae576d29649 to your computer and use it in GitHub Desktop.
Problem Statement: Write a Program to display an image after a defined set of time, using Promise where you will set the timeOut of the Image.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Sample Program to Render Image after a defined Time</title> | |
</head> | |
<body> | |
<h1>Render Image after a defined Time</h1> | |
<img id="hello" /> | |
<script type="text/javascript"> | |
function randomNumber(max) { | |
return Math.floor(Math.random() * max) + 1; | |
} | |
function loadImg() { | |
console.log('Loading'); | |
return new Promise(function (resolve, reject) { | |
resolve({ | |
img: 'https://picsum.photos/500/300?random=' + randomNumber(100), | |
timeOut: randomNumber(5000), | |
}); | |
}); | |
} | |
let time = 100; | |
function repeatingFunc() { | |
loadImg().then((res) => { | |
let imgTag = document.querySelector('#hello'); | |
imgTag.setAttribute('src', res.img); | |
document.body.appendChild(imgTag); | |
console.log( | |
`It's been ${Math.floor( | |
time / 60 | |
)} seconds. Execute the function again.` | |
); | |
time = res.timeOut; | |
}); | |
setTimeout(repeatingFunc, time); | |
} | |
setTimeout(repeatingFunc, time); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment