You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.2 KiB

  1. function adaptiveSetInterval(fn, runNow) {
  2. // unconditionally run every minute
  3. setInterval(fn, 60000);
  4. // scheduleRun() keeps calling fn and decreasing quota
  5. // every 3 seconds, until quota runs out.
  6. var quota = 0;
  7. var scheduledId = null;
  8. function scheduleRun() {
  9. if (quota > 0) {
  10. quota -= 1;
  11. clearTimeout(scheduledId);
  12. scheduledId = setTimeout(scheduleRun, 3000);
  13. fn();
  14. }
  15. }
  16. document.addEventListener("visibilitychange", function() {
  17. if (document.visibilityState == "visible") {
  18. // tab becomes visible: reset quota
  19. if (quota == 0) {
  20. quota = 20;
  21. scheduleRun();
  22. } else {
  23. quota = 20;
  24. }
  25. } else {
  26. // lost visibility, clear quota
  27. quota = 0;
  28. }
  29. });
  30. // user moves mouse: reset quota
  31. document.addEventListener("mousemove", function() {
  32. if (quota == 0) {
  33. quota = 20;
  34. scheduleRun();
  35. } else {
  36. quota = 20;
  37. }
  38. });
  39. quota = 20;
  40. scheduledId = setTimeout(scheduleRun, runNow ? 1 : 3000);
  41. }