Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Created November 8, 2021 00:29
Show Gist options
  • Save afiqiqmal/f22913edc1ef362b5c79b30d64655240 to your computer and use it in GitHub Desktop.
Save afiqiqmal/f22913edc1ef362b5c79b30d64655240 to your computer and use it in GitHub Desktop.
SetTimeout using Vuex Store
export const state = () => ({
intervalList: []
})
export const mutations = {
addWithArgument(state, {callback, args}) {
if (callback.name === undefined) {
return;
}
if (!process.env.refresh_enabled) {
return;
}
if (state.intervalList.findIndex((item) => item.name === callback.name) > -1) {
this.commit('jstimeout/remove', callback);
}
let timeout = setTimeout(() => {
let params = [];
if (!Array.isArray(args)) {
params.push(args);
} else {
args.forEach((arg) => params.push(arg));
}
callback = (typeof callback == "function") ? callback : window[callback];
callback.apply(this, params || []);
}, process.env.refresh_interval ?? 60000);
state.intervalList.push({
'name': callback.name,
'callback' : timeout
});
},
add(state, callback) {
if (callback.name === undefined) {
return;
}
if (!process.env.refresh_enabled) {
return;
}
if (state.intervalList.findIndex((item) => item.name === callback.name) > -1) {
this.commit('jstimeout/remove', callback);
}
let timeout = setTimeout(callback, process.env.refresh_interval ?? 60000);
state.intervalList.push({
'name': callback.name,
'callback' : timeout
});
},
remove(state, callback) {
if (!process.env.refresh_enabled) {
return;
}
let existCallback = state.intervalList
.find((item) => {
return item.name === callback.name;
})
?.callback;
clearTimeout(existCallback);
state.intervalList.splice(
state.intervalList
.findIndex((item) => {
return item.name === callback.name;
})
, 1
);
},
removeAll(state) {
if (!process.env.refresh_enabled) {
return;
}
state.intervalList.forEach((callback, index) => {
clearTimeout(callback?.callback);
});
state.intervalList = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment