JavaScript Stopwatch Break

Below is the code snippet. How can a button be implemented to pause the timer and then resume it when the resume button is pressed? The // marks indicate where I plan to add my pause and resume functionality. Thank you in advance for your assistance!

<head>
<script type="text/javascript">

var d1 = new Date();
d1.setHours(1,0,0);

function f(){
var h= d1.getHours();
var m= d1.getMinutes();
var s=d1.getSeconds();
m= (m<10)?"0"+m: m;
s= (s<10)? "0"+s : s;

var el= document.getElementById("inputid");
el.value= h+":"+m+":"+s;
d1.setSeconds(d1.getSeconds()-1);
if( h==0 && m==0 && s==0 ) clearTimeout(t)
var t= setTimeout("f()",1000);
}

</script>
</head>
<body>
<form><input type="text" id="inputid"></form>
<script type="text/javascript">f()</script>

//pause and resume buttons will be inserted here.
</body>

Answer №1

To halt a timeout, use the clearTimeout() function with the value returned from setTimeout, or in this scenario, t.

Check out this live demonstration: http://jsfiddle.net/tJWmH/

Another piece of advice: do not pass a string to setTimeout. Instead, pass a reference to a function like this:

var t = setTimeout(f,1000)

Instead of using this code snippet:

var t = setTimeout("f()",1000);

If you're curious about why, search for "eval is evil".

Answer №2

To implement a different strategy, consider setting a variable called paused when the button is pressed. Within your function f, if paused is true, exit the function immediately.

setInterval(function(){
  if (paused) return;
  // update the DOM
}, 1000);

input

<input type="button" value="Pause" onClick="window.paused=true" />

Check out this simple JSFiddle example

Answer №3

Give this a shot:

let currentDate = new Date();
currentDate.setHours(1,0,0);
let timer;

function startTimer() {
    let hours = currentDate.getHours();
    let minutes = currentDate.getMinutes();
    let seconds = currentDate.getSeconds();
    minutes = (minutes < 10) ? ('0'+minutes) : minutes;
    seconds = (seconds < 10) ? ('0'+seconds) : seconds;

    let element = document.getElementById("inputField");
    element.value = hours + ":" + minutes + ":" + seconds;

    if (hours == 0 && minutes == 0 && seconds == 0) {
        clearTimeout(timer)
        return;   
    }
    currentDate.setSeconds(currentDate.getSeconds() - 1);

    timer = setTimeout(startTimer, 1000);
}

function pauseTimer() {
    clearTimeout(timer);
}
function resumeTimer() {
    timer = setTimeout(startTimer, 1000);
}
resumeTimer();

To pause the timer, simply call pause(), and to resume it, call resume(). It's that simple! Note that resume() is called once at the beginning to start the countdown.

UPDATE: Make sure to check if the timer has reached zero before decrementing, and return after pausing to prevent resuming without checking.

Answer №4

I came across this code snippet and decided to incorporate it into my projects. The original post can be found here:

Timer = function(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
    window.clearTimeout(timerId);
    remaining -= new Date() - start;
  };

  this.resume = function() {
    start = new Date();
    timerId = window.setTimeout(callback, remaining);
  };

  this.resume();
};

To use the code:

var t = new Timer(function(){
 /* ... */
}, 500);

t.pause();
t.resume();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is hard coding permissions in the frontend considered an effective approach?

I'm in the process of creating an inventory management system that allows admin users to adjust permissions for other employees. Some permissions rely on others to function properly, and I need to display different names for certain permissions on the ...

Passing in additional custom post data alongside serializing with jQuery

function MakeHttpRequest( args ) { var dataToSend = "?" + $("form[name=" + args.formName + "]").serialize(); $.ajax({ type: "POST", url: args.url + dataToSend, data: { request: args.request }, su ...

Update the radio button to display the value entered in the text input field

I'm trying to implement a feature where the value of a text box can be set as the value of the selected radio button. Below is the code I have: HTML <form action="add.php" id="registration" method="post" name='registration' onsubmit="re ...

Connect the AngularJS data model with a Foundation checkbox element

I am attempting to link a model (a boolean value) to a checkbox created with Foundation (Zurb). I have created a small demonstration displaying the issue: http://jsfiddle.net/JmZes/53/ One approach could involve simply creating a function that triggers o ...

How to use Javascript to fetch HTML content from an external website

Is it possible to access and retrieve scores from for a specific week using AJAX or JSON technology? Each game on the website seems to have a unique class which could make retrieving score information easier. Any guidance or assistance would be greatly ap ...

Crawlers designed to handle websites with never-ending scroll feature

Currently seeking a crawler application that can analyze the JavaScript on a webpage for AJAX requests and identify functions that initiate those calls in order to retrieve all content from start to finish. I would develop this myself, but my workload is ...

Validate Bootstrap - Transmit data from all form fields to external PHP script

Is there a way to send all input field values to a remote PHP file using Bootstrap Validator? In my log in form, I have two input fields. I'm utilizing Bootstrap Validator's remote validation on both of them. However, each validation only sends ...

Is there an improved guide available for using Netbeans' new language support plug-in?

Recently, I've started working with a new server side language that is based on Javascript. It has similar functionalities to PHP, but uses Javascript syntax for processing server responses and handling logic. In terms of text editors, Netbeans is my ...

What is the best way to insert a two-worded value into the value attribute of an input tag using Express-Handlebars?

Currently, I am using the code below to render the handlebars page: router.get("/update", function(req, res) { mysql.pool.query("SELECT * FROM workouts WHERE id = ?",[req.query.id], function(err, rows, fields) { if (err) { c ...

"Automatically insert a new row into the table if the cell loses focus and is not left

Can someone assist me with adding a table row dynamically when a cell is filled and the input focus is lost? My JavaScript skills are not strong. Here is a link to the form: JSFIDDLE <table class="table table-timesheet" ng-controller="TimesheetCtrl"> ...

Ways to attach the close event to the jquery script

Hello, I'm having trouble reloading the parent page when the close button is clicked on a modal dialog. Here's my code snippet: //customer edit start $( ".modal-customeredit" ).click(function() { var myGroupId = $(this).attr('data- ...

Ways to stop jQuery from stripping the <script> elements

Is there a way to stop jquery from removing my JS default behavior? function loadPageSuccess(data) { var data = $(data).find('#content'); alert($(data).html()); $("#content").html(data); $("#page").fadeTo(100,1); } function loadP ...

Create an interface that inherits from another in MUI

My custom interface for designing themes includes various properties such as colors, border radius, navbar settings, and typography styles. interface ThemeBase { colors: { [key: string]: Color; }; borderRadius: { base: string; mobile: st ...

Utilize the dynamic duo of GridLayout and ScrollView within the Famo.us JS framework

I'm attempting to incorporate a grid layout into a scroll view using famo.us (with angular), and the most straightforward approach seems to be working. <fa-view> <fa-scroll-view fa-pipe-from="eventHandler" fa-options="scrollView"> ...

Error Alert: React Native object cannot be used as a React child within JSON, leading to an Invariant Violation

When using React-Native: To start, here is the example code of a json file: Any placeholders marked with "..." are for string values that are not relevant to the question. [ { "id": "question1" "label": "..." "option": [ { "order": 1, "name": "..."}, ...

Creating a smooth fading effect for an element within a react component

I am currently working on implementing a fade out warning/error message (styled with Bootstrap) in a React component, however, I am encountering some challenges with the timing of the fade-out effect. Up to this point, the fade out effect is functioning c ...

Transferring information from the main function to getServerSideProps

I've been facing challenges while trying to pass data from a function component to the getServerSideProps method in Next.js. As a beginner in learning Next.js, I am struggling to understand this concept. My approach involves using context from _app, b ...

The image component is missing the necessary "src" attribute even though a valid src value has been provided as a prop

I'm encountering an issue in Next.JS where a component is not recognizing the image source passed through a prop. I am providing the path of an image named "logo.jpg" from the project's public folder. The image successfully displays when used as ...

Enter a keyword in the search bar to find what you're looking

I am working on a form where users can select their occupation from a list that is stored in a separate .js file. The list includes various occupations like 'AA Patrolman' and 'Abattoir Inspector'. var occupationSelect = "<select id ...

Ensure prototype is easily accessible within vuex

Within my app.js file, I implemented a functionality to enable translation in Vue: Vue.prototype.trans = string => _.get(window.i18n, string); This feature works perfectly when used in my Vue files: {{ trans('translation.name') }} However, ...