I have found myself using the setTimeout and clearTimeout for different types of functions like making a countdown timer on buttons showing how many seconds left until a redirect, or running some sort of functionality every random interval between 5 and 20 seconds for a certain amount of time lets say 6 seconds.
If there any library that simplifies this at all? I thought of some sort of api that could work in a lot of these scenarios:
timer({
timer_type: "count_down",
timer_end: 5000,
timer_start: 0,
interval: 1000, // if interval is 0 then interval becomes random between 1000 and 2000 ms
interval_rand_min: 1000, // interval is ignored if this is and interval_rand_max is used
interval_rand_max: 1000,
before_start_callback: first_callback,
main_callback: main_callback,
finish_callback: finish_callback
})
A countdown timer from 5 secs to 0 out putting the current count:
timer({
timer_type: "count_down",
timer_start: 5000,
interval: 1000,
main_callback: () => {console.log(i + "seconds left")},
finish_callback: () => {console.log("countdown finished")}
})
This is a countup timer from 0 secs to 5 out putting the current count
timer({
timer_type: "count_up",
timer_end: 5000,
timer_start: 0,
interval: 1000,
main_callback: () => {console.log(i)},
finish_callback: () => {console.log("finished")}
})
etc...
Any help would be great!
Take a look at EasyTimer.js, it seems to have almost everything you need.
A random interval is something you should really be doing yourself, it's not really the job of a library to decide how to specifically implement this.