简体   繁体   中英

How to call a setInterval function

Instead of setInterval running upon refresh, I'd like it to run upon clicking on the start button & go up to time. I tried almost every variation for the past hours & it didn't work without any errors.

Instead the timer stops which makes sense if time > 2. Therefore, I am not sure how I can make timer restart once start gets click and for the timer to stop once time reached (ie 2 seconds)

HTML

<script src='https://api.chipware.co.za/js/flipclock-min.js'></script><script  src="./script.js"></script>
<button style="width:200px; height: 50px;" id="start">Start</button>
<button style="width:200px; height: 50px;"onclick="submit()" id="stop">Submit</button>

JS

let time = 2;
var clock = $('.clock').FlipClock(0, {
clockFace: 'HourlyCounter',
countdown: false });

function submit(){
clock.stop();
}

var element_ = document.getElementById("start");
    element_.addEventListener('click', function(){
    start(time);
    });

function start(time){
countup = setInterval(function () { 
    if(clock.getTime().time > time) { 
    clock.stop();
    clearInterval(countup);
    }
    else{
    var element = document.getElementById("stop");
    element.addEventListener('click', function(){
    submit();
    });
}
})}; 

Also unsure why this code runs w/o error by itself but in chrome extension, it gives:

Uncaught TypeError: $(...).FlipClock is not a function

Your missing flipclock library I just added and update the code now it work.

 let time = 2; var clock = $('.clock').FlipClock(0, { clockFace: 'HourlyCounter', countdown: false }); function submit(){ clock.stop(); } var element_ = document.getElementById("start"); element_.addEventListener('click', function(){ start(time); }); function start(time){ countup = setInterval(function () { console.log(clock.getTime().time,time) if(clock.getTime().time > time) { clock.stop(); clearInterval(countup); } else{ var element = document.getElementById("stop"); element.addEventListener('click', function(){ submit(); }); } })};
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/flipclock/0.7.7/flipclock.min.js" integrity="sha512-Vy4ftjkcjamOFPNSK7Osn8kYhF7XDcLWPiRvSmdimNscisyC8MkhDlAHSt+psegxRzd/q6wUC/VFhQZ6P2hBOw==" crossorigin="anonymous"></script> <button style="width:200px; height: 50px;" id="start">Start</button> <button style="width:200px; height: 50px;"onclick="submit()" id="stop">Submit</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM