Skip to content

Instantly share code, notes, and snippets.

@nekoneko-wanwan
Last active August 29, 2015 14:10
Show Gist options
  • Save nekoneko-wanwan/60cef6759d8df621b10c to your computer and use it in GitHub Desktop.
Save nekoneko-wanwan/60cef6759d8df621b10c to your computer and use it in GitHub Desktop.
クロージャを使ってカウントアップ処理
function playFunc(n) {
if(n === 1){
console.log('奇数');
} else {
console.log('偶数');
}
}
function counter(){
var count = 0;
return function() {
if(count === 2 ) {
count = 1;
} else {
count++;
}
playFunc(count);
};
}
var num = counter();
setInterval(function(){
num();
}, 1000);
function counter(n) {
var cnt = n || 0;
return {
get: function() {
cnt++;
return cnt;
},
reset: function() {
cnt = 0;
return cnt;
}
};
}
var countUp = counter(0);
console.log(countUp.get()); // 1
console.log(countUp.get()); // 2
console.log(countUp.get()); // 3
console.log(countUp.reset()); // 0
console.log(countUp.get()); // 1
console.log(countUp.get()); // 2
console.log(countUp.get()); // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment