Fix setTimeout does not delay issue and move to a shared function