如题,用到闭包,和settimeout函数怎么解决?
也欢迎php的实现
如题,用到闭包,和settimeout函数怎么解决?
也欢迎php的实现
<code>var count = (function() {
var timer;
var i = 0;
function change(tar) {
i++;
console.log(i);
if (i === tar) {
clearTimeout(timer);
return false;
}
timer = setTimeout(function() {
change(tar)
}, 1000)
}
return change;
})()
count(50)</code>
<code>(function(){
var i=0;
var end=setInterval(function(){
if(i>=50){
clearInterval(end);
}
console.log(i);
i++;
},1000);
})()</code>
用setTimeout的话,就不需要clear了。
<code>void function loop(i) {
if (i <= 50) {
console.log(i);
setTimeout(loop.bind(this, ++i), 1000);
}
}(1);</code>好像没用到闭包,那么这样吧:
<code>void function loop(i) {
if (i <= 50) {
console.log(i);
setTimeout(function() {loop(++i);}, 1000);
}
}(1);</code>OK,这样就有闭包了。
立即学习“Java免费学习笔记(深入)”;
function Count(){
<code> var counter=0;
function addCount(){
counter++;
console.log(counter);
if(counter==50){
return false;
}
setTimeout(addCount,1000);
}
return addCount;
}
var myCount=new Count();
myCount();</code>
<code>var task = function (){
var val = 0;
var target = 50;
(function add(){
val++;
if(val === target)
return;
setTimeout(add, 1000);
})();
}</code>
你这个停不下来吧
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号