参考
https://my.oschina.net/senit/blog/743163
和本地localstorage置换时间的验证码计时器
拆除jquery做到不依赖第三方库

for example
在react中使用

  1. const codeTimer = function (el:HTMLElement, wait:number) {
  2. this.el = el
  3. this.wait = wait
  4. this.load = () => {
  5. //获取缓存中的值
  6. let timers = this.getLocalDelay();
  7. if (timers.lastname == null || timers.lastname == 0) {
  8. this.el.innerHTML = '获取验证码'
  9. this.wait = wait
  10. return;
  11. }
  12. if (timers.lastname > 0) {
  13. this.el.style.color = 'gray'
  14. }
  15. this.el.innerHTML = "剩余(" + timers.lastname + ")秒"
  16. let timer = setInterval( () => {
  17. if (timers.lastname > 0) {
  18. timers.lastname--;
  19. this.el.style.color = 'gray'
  20. this.el.innerHTML = "剩余(" + timers.lastname + ")秒"
  21. this.setLocalDelay(timers.lastname);
  22. } else {
  23. clearInterval(timer);
  24. this.el.style.color = 'orange'
  25. this.el.innerHTML = '获取验证码'
  26. this.wait = wait
  27. }
  28. }, 1000);
  29. }
  30. this.time = () => {
  31. this.setLocalDelay(this.wait);
  32. if (this.wait == 0) {
  33. this.el.style.color = 'orange'
  34. this.el.innerHTML = '获取验证码'
  35. this.wait = wait
  36. this.setLocalDelay(this.wait);
  37. } else {
  38. let timer = setInterval( () => {
  39. console.log(el);
  40. if (this.wait > 0) {
  41. this.wait--;
  42. this.el.style.color = 'gray'
  43. this.el.innerHTML = "剩余(" + this.wait + ")秒"
  44. this.setLocalDelay(this.wait);
  45. } else {
  46. clearInterval(timer);
  47. this.el.style.color = 'orange'
  48. this.el.innerHTML = '获取验证码'
  49. this.wait = wait
  50. }
  51. }, 1000);
  52. }
  53. }
  54. this.setLocalDelay = (time) => {
  55. //location.href作为页面的唯一标识,可能一个项目中会有很多页面需要获取验证码。
  56. localStorage.setItem("lastname" + location.href, time);
  57. }
  58. this.getLocalDelay = () => {
  59. const LocalDelay: any = {};
  60. LocalDelay.lastname = localStorage.getItem("lastname" + location.href);
  61. return LocalDelay;
  62. }
  63. }
  64. // 使用
  65. let mCodeTimer
  66. export default class Login extends Component<LoginProps> {
  67. componentDidMount() {
  68. const btn = document.querySelector('#get_verify_code_btn') as HTMLElement
  69. mCodeTimer = new codeTimer(btn, 10)
  70. mCodeTimer.load()
  71. }
  72. render() {
  73. <span onClick={() => {
  74. mCodeTimer.time()
  75. }}
  76. id="get_verify_code_btn">
  77. 获取验证码
  78. </span>
  79. }
  80. }

参考

https://my.oschina.net/senit/blog/743163