gpt4 book ai didi

javascript - 运行一个函数指定的次数

转载 作者:数据小太阳 更新时间:2023-10-29 04:03:52 25 4
gpt4 key购买 nike

function runAgain()
{
window.setTimeout(foo, 100);
}

function foo()
{
//Do somthing
runAgain();
}

我可以使用上面的代码以一秒的间隔无限次地运行一个函数。

运行函数定义次数的标准方法是什么。比方说,我希望 foo() 以 1 秒的间隔运行 5 次。

编辑 据说在 Javascript 中应该避免使用全局变量。有没有更好的办法?

根据答案的输入,我创建了一个这样的函数:(工作示例:http://jsbin.com/upasem/edit#javascript,html)

var foo = function() {
console.log(new Date().getTime());
};


var handler = function(count) {
var caller = arguments.callee;
//Infinite
if (count == -1) {
window.setTimeout(function() {
foo();
caller(count);
}, 1000);
}
if (count > 0) {
if (count == 0) return;
foo();
window.setTimeout(function() {
caller(count - 1);
}, 100);
}
if (count == null) {foo(); }
};

handler(-1); //Runs infinite number of times
handler(0); //Does nothing
handler(2); //Runs two times
handler(); //Runs foo() one time

最佳答案

var counter = 1;
function foo()
{
if (counter < 5){
counter++
window.setTimeout(foo, 1000);
}
}

foo()// it will run 5 times;

LIVE DEMO


带有“静态变量”的版本:

function foo() {
if (typeof foo.counter == 'undefined') {
foo.counter = 0;
}
alert("Run No. " + (++foo.counter));

if (foo.counter < 5) {
setTimeout(function() {
foo(foo.counter + 1);
}, 400);
}
}

foo();

LIVE DEMO


隐藏输入的版本

function foo() {
var counter = document.getElementById('counter');
var counterValue = parseInt(counter.value, 10);
alert('Run No. ' + counterValue);
if (counterValue< 5) {
counter.value = counterValue + 1;
window.setTimeout(foo, 400);
}
}

foo();​

LIVE DEMO


关闭版本:

var x = function() {
var counter = 1;

(function foo() {
alert('Run No. ' + counter);

if (counter < 5) {
counter++;
setTimeout(foo, 400);
}
})();
};
x();​

LIVE DEMO

关于javascript - 运行一个函数指定的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9859145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com