@v-grabko

Почему не правильно работает проверка времени жизни?

window.Cache = {
    Get: function (name, call, time) {
        var st = this.Storage();
        var data = st.getItem(name);
        if (data != undefined) {
            data = JSON.parse(data);
            var times = parseInt(new Date().getTime() / 1000) - data.time;
            console.info(times);
            if (times >= time) { // не срабатывает
                return data.data;
            } else {
                st.removeItem(name);
                var gg = call();
                st.setItem(name, JSON.stringify({
                    data: JSON.stringify(gg),
                    time: parseInt(new Date().getTime() / 1000)
                }));
                return gg;
            }
        } else {
            var gg = call();
            st.setItem(name, JSON.stringify({
                data: JSON.stringify(gg),
                time: parseInt(new Date().getTime() / 1000)
            }));
            return gg;
        }
    },
    Set: function (name, value) {
        var st = this.Storage();
        st.setItem(name, JSON.stringify({
            data: JSON.stringify(value),
            time: parseInt(new Date().getTime() / 1000)
        }));
    },
    Del: function (name) {
        var st = this.Storage();
        st.removeItem(name);
    },
    Clear: function () {
        var st = this.Storage();
        st.clear();
    },
    /**
     * Создаёт обьект localStorage. Если произошла ошибка емулирует localStorage. 
     * (все данные хранит в озу, пропадают при перегрузке страницы). 
     */
    Storage: function () {
        try {
            return window['localStorage'];

        } catch (e) {
            return {
                storage: {},
                clear: function () {
                    delete this.storage;
                    this.storage = {};
                },
                getItem: function (key) {
                    return this.storage[key];
                },
                removeItem: function (key) {
                    return delete this.storage[key];
                },
                setItem: function (key, value) {
                    this.storage[key] = value;
                }
            };
        }
    }

};

Почему то всегда срабатывает замыкание.
А console.info(times);
возвращает 3, 6 , 100 и т.д.
  • Вопрос задан
  • 123 просмотра
Решения вопроса 1
@v-grabko Автор вопроса
window.Cache = {
    Get: function (name, call, time) {
        var st = this.Storage();
        var data = st.getItem(name);
        if (data != undefined) {
            data = JSON.parse(data);
            var times = parseInt(new Date().getTime() / 1000) - data.time;
            console.info(times);
            console.info(time);
            if (times <= time) { 
                console.info('cache');
                return data.data;
            } else {
                console.info('STcache');
                st.removeItem(name);
                var gg = call();
                st.setItem(name, JSON.stringify({
                    data: JSON.stringify(gg),
                    time: parseInt(new Date().getTime() / 1000)
                }));
                return gg;
            }
        } else {
            console.info('NO cache');
            var gg = call();
            st.setItem(name, JSON.stringify({
                data: JSON.stringify(gg),
                time: parseInt(new Date().getTime() / 1000)
            }));
            return gg;
        }
    },
    Set: function (name, value) {
        var st = this.Storage();
        st.setItem(name, JSON.stringify({
            data: JSON.stringify(value),
            time: parseInt(new Date().getTime() / 1000)
        }));
    },
    Del: function (name) {
        var st = this.Storage();
        st.removeItem(name);
    },
    Clear: function () {
        var st = this.Storage();
        st.clear();
    },
    /**
     * Создаёт обьект localStorage. Если произошла ошибка емулирует localStorage. 
     * (все данные хранит в озу, пропадают при перегрузке страницы). 
     */
    Storage: function () {
        try {
            return window['localStorage'];

        } catch (e) {
            return {
                storage: {},
                clear: function () {
                    delete this.storage;
                    this.storage = {};
                },
                getItem: function (key) {
                    return this.storage[key];
                },
                removeItem: function (key) {
                    return delete this.storage[key];
                },
                setItem: function (key, value) {
                    this.storage[key] = value;
                }
            };
        }
    }

};
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Sanasol
@Sanasol Куратор тега JavaScript
нельзя просто так взять и загуглить ошибку
Данные-то какие передаете?

Логика вообще не ясна, как вы используете аргумент time в вызове Get.
Кажется что это должно быть время жизни, но у вас получается наоборот. В коде если время жизни больше чем переданное время жизни, то возвращаем из кеша значение - бесконечное время жизни.

ps.
в целом идея какая-то ужасная.
Почему GET УСТАНАВЛИВАЕТ значения которые получены из колбека какого-то.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы