setInterval 不调用带参数的函数 [英] setInterval not call function with arguments
问题描述
我试图使用 setInterval 重复调用一个函数.当我调用一个没有参数的函数时,它可以工作.但是,在调用带参数的函数时,该函数只会被调用一次.
I was trying to repeatedly call a function using setInterval. When I call a function without arguments, it works. However, on calling a function with arguments, the function is called only once.
这里是js小提琴
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="./check.js">
</script>
</body>
</html>
check.js 不带参数 - 有效
check.js Without arguments - works
setInterval(myfun,100)
var mycounter = 0;
function myfun()
{
console.log(mycounter++)
}
check.js 带参数 - 不起作用
check.js With arguments - does not work
setInterval(myfun(0),1000)
function myfun(mycounter)
{
console.log(mycounter++)
}
推荐答案
当您添加括号时,函数会立即被调用,并且返回的结果用于区间中,在您的情况下,这是<的默认返回值代码>未定义代码>.
When you add the parentheses the function is called right away, and the returned result is used in the interval, which in your case is the default return value of undefined
.
你真正在做的是
var result = myfun(0); // returns undefined
setInterval(result, 1000); // no go, result is undefined
function myfun(mycounter) {
}
如果你想传递参数,最简单的就是使用匿名函数
if you want to pass arguments, the easiest is to just use an anonymous function
setInterval(function() {
myfun(0);
}, 1000);
现代浏览器(不是 IE9 及以下)现在支持直接在 setInterval
Modern browser (not IE9 and below) now support passing arguments directly in setInterval
setInterval(myfun, 1000, 0); // "0" is passed as the first argument to myfun()
当然,只有当变量存在于区间回调函数之外的作用域内时,才能增加变量
of course, incrementing the variable can only be done if the variable exists in a scope outside the callback function for the interval
这篇关于setInterval 不调用带参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!