点击按钮后javascript函数继续运行

时间:2018-02-18 07:05:06

标签: javascript

这可能是非常简单的逻辑,但此时此刻我没有登录。  让我们说我有一个名为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);

}
&#13;
<div id="countdown">
  <div id='tiles'></div>
  <div class="labels">
    <li>Days</li>
    <li>Hours</li>
    <li>Mins</li>
    <li>Secs</li>
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

你可以使用递归。

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();

答案 1 :(得分:-1)

听起来你想使用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