使用函数setinterval javascript错误使用函数
using function in setinterval javascript error using function
我写了一个简单的定时器为什么这段代码不正确is说Uncaught ReferenceError: a没有定义为什么?
function timeee(sec) {
document.getElementById("main").innerHTML = sec;
--sec;
if (sec == -1) {
clearInterval(cleartext);
}
}
function timer() {
var a = document.getElementById("time").value;
var cl = setInterval("timeee(a)", 1000);
window.cleartext = cl;
}
正如您在另一个问题中看到的,当您将setInterval
与字符串一起使用时,该函数是在全局作用域中运行的。但是,您的a
变量仅在本地设置,因此timeee()
函数无法看到它。
尝试使用:
function timer() {
var a = document.getElementById("time").value;
var cl = setInterval(function() { timeee(a) }, 1000);
window.cleartext = cl;
}
或者如果您真的想使用字符串,则将a
定义为全局变量:
var a;
function timer() {
a = document.getElementById("time").value;
var cl = setInterval("timeee(a)", 1000);
window.cleartext = cl;
}
为什么?
范围。
考虑:
function timer() {
var a = document.getElementById("time").value;
var cl = setInterval("timeee(a)", 1000);
window.cleartext = cl;
}
a是局部作用域,但是timeee(a)将从全局作用域调用。它不能访问和。试一试:
var cl = setInterval(function(){timeee(a)}, 1000);
所以在闭包中保留的值a注意,这样每次都会传递相同的a值,所以你也需要解决这个问题(Banana的答案是一个选项)。
经过一番思考,我最好的猜测是对"a"的引用不是一个合适的闭包。
这样想:你正在传递一个字符串给setInterval
。隐式地,当您将字符串传递给setInterval
或setTimeout
时,某处的eval()
正在被调用。因为在运行时,解释器不知道变量a
在其他地方被使用,所以它会丢弃它。然后,当执行eval
时,参数a
不再存在。
现在看看你的问题的解决方案:
function timer() {
var a = document.getElementById("time").value;
var cl = setInterval(function() { timeee(a) }, 1000);
window.cleartext = cl;
}
因为解释器知道a
以后还会被使用,所以它不会被销毁。
相关文章:
- Node.js v6.2.0类扩展不是函数错误
- Javascript搜索函数错误
- Chrome Javascript日期构造函数错误
- 浏览器中出现javascript初始大写函数错误
- Createjs冲突问题localToLocal不是函数错误
- Java脚本函数错误
- 更新带有Javascript函数错误的变量
- 如何将对象插入对象列表的开头,当它有 unshift 不是函数错误
- 在将 Pickadate 与 Meteor 一起使用时,未定义不是函数错误
- 运行咕噜咕噜咕噜抛出 _.object 不是函数错误
- 了解函数(错误、数据)回调
- javascript中的typeof()函数错误
- 我一直在获取angularjs服务不是函数错误(LoginService.login不是函数)
- HTML5拖拽&drop正在抛出undefined不是函数错误
- Google Maps API a.lat不是函数错误
- getItemAtIndex不是函数错误
- Javascript停止函数错误
- 对话框函数错误无效函数
- Javascript 自定义函数错误
- 因果报应单元测试'未定义'不是函数错误