Skip to content

Instantly share code, notes, and snippets.

@greggnakamura
Last active August 29, 2015 14:14
Show Gist options
  • Save greggnakamura/6a8b35d2294afaeb49d1 to your computer and use it in GitHub Desktop.
Save greggnakamura/6a8b35d2294afaeb49d1 to your computer and use it in GitHub Desktop.
Javascript: setInterval example
(function () {
var speed = 500,
i = 0,
doSomething = function () {
console.log('doSomething() executed ' + (i + 1) + ' times');
i++;
if (i > 4) {
// stop when condition is met
clearInterval(timer);
}
};
// setInterval to call 'doSomething'
// run every 500ms
// add ID to 'timer'
var timer = setInterval(doSomething, speed);
})();
(function () {
var speed = 500,
i = 0,
doSomething = function () {
console.log('doSomething() executed ' + (i + 1) + ' times');
i++;
};
setTimeout(function() {
doSomething();
setTimeout(function() {
doSomething();
setTimeout(function() {
doSomething();
setTimeout(function() {
doSomething();
setTimeout(function() {
doSomething();
}, speed);
}, speed);
}, speed);
}, speed);
}, speed);
})();
@greggnakamura
Copy link
Author

Output:

"doSomething() executed 1 times"
"doSomething() executed 2 times"
"doSomething() executed 3 times"
"doSomething() executed 4 times"
"doSomething() executed 5 times"

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