Introduction
Here I show a random color generator for a div using TypeScript and change the color of the div at regular intervals of time using TypeScript. We use the setInterval method in this example. The setInterval method creates a timer that calls the specified function at the specified interval in milliseconds.
Coding
Random_Colors.ts
- class Generate_Random_Color
- {
- Random_Color()
- {
- setInterval(() => {
- this.Color();
- }, 1000);
- }
- Color()
- {
- var color = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ","
- +
- Math.floor(Math.random() * 255) + ")";
-
- document.getElementById("content").style.color = color;
- }
- }
- window.onload = () =>
- {
- var obj = new Generate_Random_Color();
- obj.Random_Color();
- };
- Generate_Random_Color_Demo.html
- <
- !DOCTYPE html >
- <
- html lang = "en"
- xmlns = "http://www.w3.org/1999/xhtml" >
- <
- head >
- <
- meta charset = "utf-8" / >
- <
- title > TypeScript HTML App < /title>
- <
- link rel = "stylesheet"
- href = "app.css"
- type = "text/css" / >
- <
- script src = "Random_Colors.js"
- type = "text/javascript" > < /script>
- <
- /head>
- <
- body >
- <
- h3 > Generate Random Colores In TypeScript < /h3>
- <
- div id = "content"
- font - size: large ">
- Welcome to Csharpcorner < br / >
- Welcome to Csharpcorner < br / >
- Welcome to Csharpcorner < br / >
- Welcome to Csharpcorner < br / >
- Welcome to Csharpcorner < br / >
- Welcome to Csharpcorner
- <
- /div>
- <
- /body>
- <
- /html>
Random_Colors.js
- var Generate_Random_Color = (function() {
- function Generate_Random_Color() {}
- Generate_Random_Color.prototype.Random_Color = function() {
- var _this = this;
- setInterval(function() {
- _this.Color();
- }, 1000);
- };
- Generate_Random_Color.prototype.Color = function() {
- var color = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," +
- Math.floor(Math.random() * 255) + ")";
- document.getElementById("content").style.color = color;
- };
- return Generate_Random_Color;
- })();
- window.onload = function() {
- var obj = new Generate_Random_Color();
- obj.Random_Color();
- };
Output
For more information, download the attached sample application.