![](/img/trans.png)
[英]Javascript - Execute function every x seconds, but only execute function 3 times
[英]Javascript: Execute a function for every 3 seconds for One minute
我需要每3秒執行一次功能,直到1分鍾。 當用戶將注意力集中在輸入框上時,應調用此方法。
我已經通過谷歌搜索嘗試過,但是其中大多數都帶有setInterval函數。 我知道setInterval可用於在特定時間間隔內調用函數。 但是,如果時間到1分鍾,我需要停止該操作。
請給我建議。
嘗試這樣-
var time = 0;
var interval = setInterval(function(){
// do your stuf
time += 3000;
if(time >= (1000*60)){ // one minute
clearInterval(interval);
}
},3000);
在文本框的輸入焦點上嘗試以下操作:
var startTime = new Date().getTime();
var interval = setInterval(function(){
if(new Date().getTime() - startTime > 60000){
clearInterval(interval);
return;
}
//do whatever here..
}, 3000);
演示代碼:
$('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.