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
  1. class Generate_Random_Color
  2. {
  3. Random_Color()
  4. {
  5. setInterval(() => {
  6. this.Color();
  7. }, 1000);
  8. }
  9. Color()
  10. {
  11. var color = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ","
  12. +
  13. Math.floor(Math.random() * 255) + ")";
  14. //change the text color with the new random color
  15. document.getElementById("content").style.color = color;
  16. }
  17. }
  18. window.onload = () =>
  19. {
  20. var obj = new Generate_Random_Color();
  21. obj.Random_Color();
  22. };
  23. Generate_Random_Color_Demo.html
  24. <
  25. !DOCTYPE html >
  26. <
  27. html lang = "en"
  28. xmlns = "http://www.w3.org/1999/xhtml" >
  29. <
  30. head >
  31. <
  32. meta charset = "utf-8" / >
  33. <
  34. title > TypeScript HTML App < /title>
  35. <
  36. link rel = "stylesheet"
  37. href = "app.css"
  38. type = "text/css" / >
  39. <
  40. script src = "Random_Colors.js"
  41. type = "text/javascript" > < /script>
  42. <
  43. /head>
  44. <
  45. body >
  46. <
  47. h3 > Generate Random Colores In TypeScript < /h3>
  48. <
  49. div id = "content"
  50. font - size: large ">
  51. Welcome to Csharpcorner < br / >
  52. Welcome to Csharpcorner < br / >
  53. Welcome to Csharpcorner < br / >
  54. Welcome to Csharpcorner < br / >
  55. Welcome to Csharpcorner < br / >
  56. Welcome to Csharpcorner
  57. <
  58. /div>
  59. <
  60. /body>
  61. <
  62. /html>
Random_Colors.js
  1. var Generate_Random_Color = (function() {
  2. function Generate_Random_Color() {}
  3. Generate_Random_Color.prototype.Random_Color = function() {
  4. var _this = this;
  5. setInterval(function() {
  6. _this.Color();
  7. }, 1000);
  8. };
  9. Generate_Random_Color.prototype.Color = function() {
  10. var color = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," +
  11. Math.floor(Math.random() * 255) + ")";
  12. document.getElementById("content").style.color = color;
  13. };
  14. return Generate_Random_Color;
  15. })();
  16. window.onload = function() {
  17. var obj = new Generate_Random_Color();
  18. obj.Random_Color();
  19. };
Output
Animation1.gif
For more information, download the attached sample application.