Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push/play setTimeout function

I want to show clock with some difference . below given code is working fine for me. but i want to push and play this time whenever user want. i want to push and resume SetTimeout function .any one have any idea how to do that ?

enter image description here

$("#push").click(function () {

});

$("#play").click(function () {
    show();
});

function show() {
    var Digital = new Date();
    var time2 = Digital.getTime();
    var time1 = 1403517957984;
    var diff = Math.abs(new Date(time2) - new Date(time1));
    var seconds = Math.floor(diff / 1000); //ignore any left over units smaller than a second
    var minutes = Math.floor(seconds / 60);
    seconds = seconds % 60;
    var hours = Math.floor(minutes / 60);
    minutes = minutes % 60;
    if (hours < 10) hours = "0" + hours;
    if (minutes < 10) minutes = "0" + minutes;
    if (seconds < 10) seconds = "0" + seconds;
    $('#worked_time').html(hours + ":" + minutes + ":" + seconds);
    setTimeout("show()", 1000);
}
show();
like image 817
amit gupta Avatar asked Sep 30 '22 12:09

amit gupta


1 Answers

This is a mix of the respond of @colburton and @TwiStar

Respond correctly to the answer

var isPlaying = true;
var toHandle = null;

$("#push").click(function () {
    isPlaying = false;
    if (toHandle !== null)
    {
       clearTimeout(toHandle);
       toHandle = null;
    }
});

$("#play").click(function () {
    isPlaying = true;
    show();
});

function show() {
    if (isPlaying) {
        toHandle = null;
        var Digital = new Date();
        var time2 = Digital.getTime();
        var time1 = 1403517957984;
        var diff = Math.abs(new Date(time2) - new Date(time1));
        var seconds = Math.floor(diff / 1000); //ignore any left over units smaller than a second
        var minutes = Math.floor(seconds / 60);
        seconds = seconds % 60;
        var hours = Math.floor(minutes / 60);
        minutes = minutes % 60;
        if (hours < 10) hours = "0" + hours;
        if (minutes < 10) minutes = "0" + minutes;
        if (seconds < 10) seconds = "0" + seconds;
        $('#worked_time').html(hours + ":" + minutes + ":" + seconds);

        toHandle = setTimeout("show()", 1000);
    }
}
show();
like image 55
Orelsanpls Avatar answered Oct 07 '22 21:10

Orelsanpls