Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Small timer
function(
f, // function to be run
t, // time between call
n // number of iteration
){
!function c(){ // timer function
0<n--&&f()+setTimeout(c,t) // if iteration left, launch callback & timeout
}() // autolaunch the timer
}
function(f,t,n){!function c(){0<n--&&f()+setTimeout(c,t)}()}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 JEREMY BARBE http://www.shwaark.com
THANK TO subzey FOR HELP
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "timerFunction",
"description": "A small timer function",
"keywords": [
"timer",
"iteration"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b> Hello ! Hello ! Hello ! Hello !</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var interval = function(f,t,n){!function c(){0<n--&&f()+setTimeout(c,t)}()}
interval(function(){
document.getElementById( "ret" ).innerText += " Hello !";
}, 100, 4);
</script>
@subzey

This comment has been minimized.

Copy link

@subzey subzey commented Jul 27, 2011

A small but handy function. Nice job!

Few notes and suggestions:
We can safely decrement n instead of incrementing j. Also, we can shave some bytes replacing ?: with &&. Currently, callback is called at least once even if n is non-positive or NaN, IMHO, it's counter-intuitive.
Summarizing all the above we get something like:
function(f,t,n){!function c(){0<n--&&f()+setTimeout(c,t)}()}

@CapMousse

This comment has been minimized.

Copy link
Owner Author

@CapMousse CapMousse commented Jul 27, 2011

Thanks for your suggestions !

I don't know the && trick, I update the code now !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment