1. function invalidateCache(input, cacheTime) {
  2. // Store the input in a cache object with a timestamp
  3. if (!window.cache) {
  4. window.cache = {};
  5. }
  6. window.cache[input] = Date.now();
  7. // Function to check if the cache has expired
  8. const checkCache = () => {
  9. const now = Date.now();
  10. for (const key in window.cache) {
  11. if (now - window.cache[key] > cacheTime) {
  12. delete window.cache[key]; // Remove expired cache entry
  13. }
  14. }
  15. };
  16. // Set a timeout to periodically check and invalidate the cache
  17. window.setTimeout(checkCache, cacheTime);
  18. // Return a function to invalidate the cache immediately for a specific input
  19. return () => {
  20. delete window.cache[input]; // Invalidate cache for the given input
  21. };
  22. }
  23. // Example usage:
  24. // Invalidate cache for input "myInput" after 5 seconds
  25. const invalidateMyInput = invalidateCache("myInput", 5000);
  26. // To invalidate the cache immediately for "myInput":
  27. // invalidateMyInput();

Add your comment