[英]Javascript: Execute a function for every 3 seconds for One minute
I need to execute a function for every 3 sec upto 1 minutes. 我需要每3秒执行一次功能,直到1分钟。 This should be called when a user focus on the input box.
当用户将注意力集中在输入框上时,应调用此方法。
I have tried by Googling but most of them come-up with setInterval function. 我已经通过谷歌搜索尝试过,但是其中大多数都带有setInterval函数。 I knew that the setInterval can be used to call a function for certain time interval.
我知道setInterval可用于在特定时间间隔内调用函数。 But i need to stop that if the time reaches 1 min.
但是,如果时间到1分钟,我需要停止该操作。
Please suggest me on this. 请给我建议。
Try like this - 尝试这样-
var time = 0;
var interval = setInterval(function(){
// do your stuf
time += 3000;
if(time >= (1000*60)){ // one minute
clearInterval(interval);
}
},3000);
Try this on input focus of textbox: 在文本框的输入焦点上尝试以下操作:
var startTime = new Date().getTime();
var interval = setInterval(function(){
if(new Date().getTime() - startTime > 60000){
clearInterval(interval);
return;
}
//do whatever here..
}, 3000);
Demo Code: 演示代码:
$('input').one('focus',function(){
var startTime = new Date().getTime();
var interval = setInterval(function(){
if(new Date().getTime() - startTime > 60000){
clearInterval(interval);
alert('interval cleared');
return;}console.log('test')}, 3000);})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.