Last active
August 29, 2015 14:14
-
-
Save greggnakamura/6a8b35d2294afaeb49d1 to your computer and use it in GitHub Desktop.
Javascript: setInterval example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
"doSomething() executed 1 times"
"doSomething() executed 2 times"
"doSomething() executed 3 times"
"doSomething() executed 4 times"
"doSomething() executed 5 times"