我怎樣才能重複調用一個javascript函數(repeatedFunction()
),但是讓它成爲我們說的alert("This function is being executed for the first time")
僅在repeatedFunction()
第一次被激活,但是//other code
總是被激活?另外,如何讓alert()
允許再次激活一次,就像repeatedFunction()
再次被執行一樣?如何使功能的一部分只執行一次,直到它被允許執行,否則
回答
功能是對象。您可以設置(以後清除)標記的功能,如果你喜歡:
function repeatedFunction() {
if (!repeatedFunction.suppress) {
alert("This function is being executed for the first time");
repeatedFunction.suppress = true;
}
// ...other code here...
}
當你想重置,以獲得repeatedFunction
任何代碼都可以清除repeatedFunction.suppress
標誌:
repeatedFunction.suppress = false;
該標誌沒有有要上的功能,當然,你可以使用一個單獨的變量。
也就是說,我建議看大圖和檢查有問題的警報是否真的應該是函數的一部分都沒有。
您的解決方案似乎是最適合我的問題的解決方案!謝謝。 –
您可以設置一個標誌。比方說,你有這樣的下面的代碼:
var flagAlertExecd = false;
function repeatThis() {
if (!flagAlertExecd) {
alert("Only once...");
flagAlertExecd = true;
}
// Repeating code.
}
而且重複這個代碼,它是很好的使用setInterval
。
setInterval(repeatThis, 1000);
什麼爲downvote原因,好嗎? –
你可以通過聲明一個變量並在你的函數中增加它來做到這一點。使用if
語句,您可以檢查它被觸發了多少次。代碼:
var count = 0;
function myfunc(){
if(count==0){
alert("Triggering for the first time");
count++;
}
//Your always triggering code here
}
這甚至跟蹤了多少次的功能被觸發的記錄。如果您不想在
nth
時間內執行alert()
,它會很有用。您也可以使用布爾值。就像這樣:
var firstTime = true;
function myfunc(){
if(firstTime){
alert("Triggering for the first time");
firstTime = false;
}
//Your always triggering code here
}
第二種方法不會跟蹤了多少次的功能已被觸發的記錄,它只是確定是否該函數被調用的第一次或沒有。
這兩種方法都能正常工作。
var firstTime = true;
var myFunction = function() {
if(firstTime) {
alert("This function is being executed for the first time");
firstTime=false;
}else{
//whatever you want to do...
}
}; //firstTime will be true for the first time, after then it will be false
var milliseconds = 1000;
setInterval(myFunction, milliseconds);
//the setInterval means that myFunction is repeated every 1000 milliseconds, ie 1 second.
這將不會執行始終執行的代碼,這是第一次。再看看這個問題! – Arjun
@Arjun我修復了這個錯誤 –
的JavaScript closure approach將適合這個任務。它沒有全局變量,並將您的任務保存在一個函數中。
var closureFunc = function(){
var numberOfCalls = 0;
return function(){
if(numberOfCalls===0)
{
console.log('first run');
}
numberOfCalls++;
console.log(numberOfCalls);
};
};
var a = closureFunc(); //0
a(); //1
a(); //2
var a = closureFunc(); //drop numberOfCalls to 0
a(); //1
- 1. 只執行一次功能
- 2. 允許onclick函數只執行一次
- 3. 只允許某個UIGestureRecognizer一次執行
- 4. 執行功能只有一次
- 5. 執行功能只有一次
- 6. $直到代碼被執行另一次
- 7. 功能是否一直執行?
- 8. jQuery:不執行功能的一部分
- 9. 一次只允許執行一個jQuery函數
- 10. 其它函數中執行功能只有一次
- 11. RxJava一次只能執行一個Observable
- 12. 只允許用戶在Python中執行一次函數?
- 13. 只能執行一次的函數
- 14. 只有$。每一次執行似乎被執行
- 15. 只執行一次程序的一部分
- 16. 如何在Windows服務中每分鐘執行一次功能?
- 17. MultiTrigger只執行一次
- 18. JavaScript只執行一次
- 19. 只執行一次jquery
- 20. NSTask只執行一次
- 21. 執行ajax只有一次
- 22. 線程只執行一次
- 23. 只執行completeAjax一次
- 24. 只執行一次函數
- 25. 只有一次執行 - AJAX
- 26. 執行循環中的上一次執行時的PHP執行功能
- 27. 智能GWT JSNI只執行一次
- 28. 只能執行腳本一次
- 29. PHP代碼只能執行一次
- 30. Java:for循環只能執行一次
重播功能,您可以隨時擁有'的setInterval(myFunction的,毫秒);' –