![](/img/trans.png)
[英]Call a Javascript function every second with setInterval
[英]Call javascript function every second
我正在尝试学习JavaScript,现在尝试重复执行某项功能时立即购买,该功能似乎无效。
这是我的功能:
function heyhey(el){
el.style.position = "absolute";
el.style.top = Math.floor(Math.random()*document.body.clientHeight);
el.style.left = Math.floor(Math.random()*document.body.clientWidth);
}
heyhey(document.getElementById('random'));
//random is the id of my html div
这可行,但我希望每秒调用一次函数
我尝试重复的功能:
function heyhey(el){
el.style.position = "absolute";
el.style.top = Math.floor(Math.random()*document.body.clientHeight);
el.style.left = Math.floor(Math.random()*document.body.clientWidth);
heyhey();
}
heyhey(document.getElementById('random'));
我也试过这个:
function heyhey(el){
el.style.position = "absolute";
el.style.top = Math.floor(Math.random()*document.body.clientHeight);
el.style.left = Math.floor(Math.random()*document.body.clientWidth);
setTimeout(heyhey, 5000);
}
heyhey(document.getElementById('random'));
heyhey();
function heyhey(el)
该函数需要一个参数
setTimeout(heyhey, 5000);
您什么也没通过。 将参数指定为setTimeout
的第三个及以后的参数。
setTimeout(heyhey, 5000, el);
如果要避免递归,可以使用setInterval函数。
一个简单的例子:
var intervalID = window.setInterval(myCallback, 500);
function myCallback() {
// Your code here
}
如果要停止执行函数,则必须调用clearInterval() :
clearInterval(intervalID);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.