[英]javascript function to keep running after button is clicked
這可能是非常簡單的邏輯,但此時我無法登錄。 假設我有一個名為 mytimer() 的函數,它位於一個通用文件中。 我的意思是每個 html 頁面都鏈接到該文件。
mytimer(){...........................};
現在在另一頁的地方,當我的病情得到真。或者這樣的事情,我婉這個mytimer()
被解雇,並保持其運行一定時間。 我該怎么做呢 。 ? 任何建議將不勝感激
TIA
javascript代碼
// Set the date we're counting down to var countDownDate = new Date(<?=$date?>).getTime(); var countdown = document.getElementById("tiles"); // get tag element getCountdown(); var x = setInterval(function() { getCountdown(); }, 1000); function getCountdown() { var now = new Date().getTime(); var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); countdown.innerHTML = "<span>" + days + "</span><span>" + hours + "</span><span>" + minutes + "</span><span>" + seconds + "</span>"; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); document.getElementById("countdown").innerHTML = "EXPIRED"; forever = false; } } function pad(n) { return (n < 10 ? '0' : '') + n; } //when the accept button is triggered , i want above block code to be run like countdown timer function accept() { var id = document.getElementById("acceptbtn").getAttribute("data-id"); var xhr = new XMLHttpRequest(); xhr.onload = function() { if (this.readyState === 4 && this.status === 200) { console.log(this.responseText); } } xhr.open("GET", "ajax/acceptproduct.php?aid=" + id, true); xhr.send(); alert(id); }
<div id="countdown"> <div id='tiles'></div> <div class="labels"> <li>Days</li> <li>Hours</li> <li>Mins</li> <li>Secs</li> </div> </div>
你可以使用遞歸。
const TIMEOUT_MS = 1000
let keepGoing = true;
function doSomething() {
// do your logic here - if you want to change keep going to false to stop
if (keepGoing) {
setTimeout(doSomething, TIMEOUT_MS);
}
}
doSomething();
聽起來您想使用 window.setTimeout 函數。
var myVar;
function myThingToDo() {
// Do stuff and things
// Then call yourself again after a timeout.
myVar = setTimeout(myThingToDo, 3000);
}
// Call this where/whenever you want to kill the loop
function myStopFunction() {
clearTimeout(myVar);
}
這里有更多信息: https : //www.w3schools.com/jsref/met_win_settimeout.asp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.