Skip to content

Instantly share code, notes, and snippets.

@eguneys
Last active April 18, 2019 04:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eguneys/7023a114558b92fdd25e to your computer and use it in GitHub Desktop.
Save eguneys/7023a114558b92fdd25e to your computer and use it in GitHub Desktop.
// action that is fired at every tick
export function tickCountdown() {
return {
type: types.TICK_COUNTDOWN
};
}
export function setTimerAction(handlerProp, action) {
return (dispatch, getState) => {
// dispatch an action to set the timer for `handlerProp`
dispatch({
type: types.SET_TIMER,
handlerProp
});
// assume this is a Timer that calls passed callback at 1 sec interval
new Timer(() => {
const isContinue = getState()['timerStore'].get(handlerProp);
if (isContinue) {
const a = action();
dispatch(a);
}
return isContinue;
}).start();
}
}
export function clearTimerAction(handlerProp) {
return {
type: types.CLEAR_TIMER,
handlerProp
}
}
/// call this somewhere proper to start the countdown
/// possibly within another action
setTimerAction('countdownTimer', tickCountdown);
// possible to setup multiple timers with different names
setTimerAction('countdownTimer2', tickCountdown);
const initialState = {
};
export default createReducer(initialState, {
[types.SET_TIMER](state, {handlerProp}) {
return state.set(handlerProp, true);
},
[types.CLEAR_TIMER](state, {handlerProp}) {
return state.set(handlerProp, false);
}
});
export default class Timer {
constructor(tick) {
this.tick = tick;
}
start() {
this.decreaseCounterLoop();
}
stop() {
if (this.job) {
clearTimeout(this.job);
this.job = null;
}
}
decreaseCounterLoop() {
var self = this;
this.job = setTimeout(function() {
if (self.tick()) {
self.decreaseCounterLoop();
}
}, 1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment