Greasy Fork is available in English.

Leetcode Timer

Start a timer whenever a user loads a problem at Leetcode.com

  1. // ==UserScript==
  2. // @name Leetcode Timer
  3. // @description:en Start a timer whenever a user loads a problem at Leetcode.com
  4. // @version 1.2
  5. // @grant none
  6. // @include *://*leetcode.com/problems/*
  7. // @author ketankr9
  8. // @namespace https://greatest.deepsurf.us/users/564674
  9. // @description Start a timer whenever a user loads a problem at Leetcode.com
  10. // ==/UserScript==
  11.  
  12. /*
  13. * Choose Either Option 1 or Option 2.
  14. * Option 1: The time starts from the moment you open a url and continues forever.
  15. * Option 2: The time starts from 0 every time you open a url and continues only till the window is open. Everytime you reload the window the timer will restart from 0.
  16. */
  17. var option = 2; // Choose between 1 and 2
  18.  
  19. function countdownTimer() {
  20. var difference = +new Date() - startTime;
  21. var elapsed = "0";
  22.  
  23. var parts = {
  24. days: Math.floor(difference / (1000 * 60 * 60 * 24)),
  25. hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
  26. minutes: Math.floor((difference / 1000 / 60) % 60),
  27. seconds: Math.floor((difference / 1000) % 60)
  28. };
  29.  
  30. elapsed = Object.keys(parts)
  31. .map(part => {
  32. if (!parts[part]) return;
  33. return `${parts[part]} ${part}`;
  34. })
  35. .join(" ");
  36. document.getElementById("countdown").innerHTML = elapsed;
  37. }
  38.  
  39. var f = function(div){
  40. if(option === 1){
  41. // Option 1: The time starts from the moment you open a url and continues forever.
  42. var q = document.URL.split("problems/");
  43. if(q.length != 2) return null;
  44. q = q[1] + "time";
  45. console.log(q);
  46. if(localStorage.getItem(q) == null){
  47. localStorage.setItem(q, +new Date());
  48. }
  49. startTime = Date.parse(localStorage.getItem(q));
  50. }else{
  51. // Option 2: The time starts every time you open a url and continues till the window is open.
  52. startTime = new Date();
  53. }
  54. var el = document.createElement("div");
  55. el.className = "tool-item__2DCU";
  56. el.innerHTML = '<div id="countdown" style="font-size:20px;" ></div>';
  57. div.insertBefore(el, div.firstChild);
  58.  
  59. setInterval(countdownTimer, 1000);
  60. }
  61.  
  62. function waitForElementToDisplay(selector, time, f) {
  63. var node = document.getElementsByClassName(selector);
  64. console.log(node);
  65. if(node.length > 0) {
  66. console.log("Element Found");
  67. f(node[0])
  68. return;
  69. }
  70. setTimeout(function() {
  71. waitForElementToDisplay(selector, time, f);
  72. }, time);
  73. }
  74.  
  75. var startTime;
  76. waitForElementToDisplay("btns__1OeZ", 1000, f);