How come the default is operating when the number is specifically set to 1?

let spans = document.querySelector(`#spans`);
let hrs = document.querySelector(`#hrs`);
let mins = document.querySelector(`#mins`);
let secs = document.querySelector(`#secs`);
let start = document.querySelector(`#start`);
let stop = document.querySelector(`#stop`);
spans.style.fontSize = "10em";
let preFix = 0;
let num = 1;
let secspreNum= 0;
let minspreNum = 0;
let hrspreNum = 0;
let myFunc = ()=> {
    setInterval(()=>{
        switch (num){
            case num===1:
                mins.innerHTML = `0` + num;
                num ===0;
                secs.innerHTML =`0`+  num++; 
                
            default:
                console.log(`default test`)
        }
      
     } , 1000);
};


start.addEventListener(`click`,myFunc)       
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE-edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="spans">
    <span id="hrs">00</span>:<span id="mins">00</span>:<span id="secs">00</span><br></div>
    <button id="start">Start</button>
    <button id="stop">Stop</button>

    <script src="go2.js"></script>
</body>
</html>

Hello all, I'm currently working on building a stopwatch but I've encountered an issue during the process. I am attempting to incorporate a switch statement that will update the minutes when the seconds reach 10, however, I am facing some unexpected behavior where the default statement is being executed instead of the specified case. I initially set the 'num' variable to 1 and expected it to match 'num===1', but it seems this isn't happening as planned. Can someone please provide insights or suggestions? Thank you!

Answer №1

Here is an updated solution:

I made modifications to the querySelector and removed unnecessary template literals

let spans = document.getElementById('spans');
let hrs = document.getElementById('hrs');
let mins = document.getElementById('mins');
let secs = document.getElementById('secs');
let start = document.getElementById('start');
let stop = document.getElementById('stop');
let tId;
let num = 0;
let myFunc = () => {
  clearInterval(tId);
  tId = setInterval(function() {
    const date = new Date(null); // alternatively calculate hh,mm,ss using %60
    date.setSeconds(++num);
    const [hh, mm, ss] = date.toISOString().substr(11, 8).split(":");
    hrs.textContent = hh;
    mins.textContent = mm;
    secs.textContent = ss;
  }, 1000)
};


start.addEventListener('click', myFunc)
stop.addEventListener('click', function() {
  clearInterval(tId)
})
#spans {
  font-size: 10em
}
<!DOCTYPE html>
<html lang="en>

<head>
  <meta charset="UTF-8>
  <meta http-equiv="X-UA-Compatible" content="IE=edge>
  <meta name="viewport" content="width=device-width, initial-scale=1.0>
  <title>Document>
</head>

<body>
  <div id="spans">
    <span id="hrs">00</span>:<span id="mins">00</span>:<span id="secs">00</span><br></div>
  <button id="start">Start</button>
  <button id="stop">Stop</button>

  <script src="go2.js"></script>
</body>

</html>

Answer №2

Give this a shot:

const myFunction = () => {
    setInterval(() => {
        switch (num) {
            case 1:
                console.log(num);
                mins.innerHTML = `0` + num;
                secs.innerHTML = `0` + (num++);
                break;
                
            default:
                console.log(`Default test`);
        }
      
     }, 1000);
};

The case statement only accepts constants, not expressions as far as I know. Additionally, make sure to include a break or the code will "fall through" to the next condition.

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

Delete an entry from the list

I have a fully functional Ajax call and function that fills up a datalist. This datalist is utilized to choose from a limited list and add it to a UL element on the page. Once an option is added from the datalist to the actual list, I aim to eliminate that ...

Ways to Read JSON without Using jQuery

Exploring JSON Feed and Autocomplete As I delve into the realm of creating an autocomplete feature that fetches data from a JSON feed, I encounter a setback. Despite successfully parsing the JSON data using json2.js through JSON.parse, I am confronted wit ...

Is it permissible for me to incorporate a package from the dependencies listed in the package-lock.json file into my

I'm looking to incorporate date-fns into my project. I currently have react-datepicker, which also uses date-fns. Can I simply utilize date-fns from react-datepicker, or do I need to install it separately in my project? ...

Unable to click a button on HTML file

In my current project, there is a piece of code responsible for checking if the user is logged in or not. If the user hasn't logged in yet, they are redirected to the login page. Once the user logs in successfully, they should be able to upload conten ...

Retrieving a specific key-value pair from an object within a JavaScript array

Looking to extract a specific value from an array of objects using array.map? Check out the code snippet below: let balanceInfo = students.map((student) => { if (typeof(student) === Object){ let balance = student.balance; return balanc ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

Create a function that will repeatedly call itself at specified intervals, increment a variable, and update the class values of elements with an id matching the current value of the

I'm attempting to create a setup that cycles through different images <div id="img_box" class="shadow" onload="imgCycle(1)";> <img id="1" class='opaque imgbox selected' src="media/img ...

Converting a multipart form data string into JSON format

Can you help me figure out how to convert a multipart form data into a JSON object in Node.js? I've been looking for the right module but haven't had any luck so far. Here is an example of my form data: ------WebKitFormBoundaryZfql9GlVvi0vwMml& ...

Tips for incorporating JavaScript into your Selenium WebDriver workflow using Java

Looking to integrate JavaScript with WebDriver (Selenium 2) using Java. After following a guide listed on the Getting Started page, I found an initial instruction to run: $ ./go webdriverjs Curious about the specific folder/location where the above ...

Utilize Dojo to programmatically showcase an image

I'm facing an issue while trying to programmatically display an image using dojo. I have tried using both "dijit/Dialog" and "dojox/image/Lightbox". However, when using the Dialog method, instead of displaying the image, some random characters are sh ...

Sorting files in jquery file upload

Has anyone had experience using the jQuery-File-Upload library from https://github.com/blueimp/jQuery-File-Upload? I'm currently facing an issue and wondering if anyone could assist me in sorting the files in a different manner. By default, this scrip ...

After submitting the form, Axios sends multiple requests simultaneously

Recently, I embarked on a small project that involves using Laravel and Nuxt Js. The main objective of the project is to create a form for adding users to the database. Everything seems to be progressing smoothly, but there's a minor issue that I&apos ...

Leverage the controller's properties and methods within the directive

My situation involves a variety of inputs, each with specific directives: <input mask-value="ssn" validate="checkSsn"/> <input mask-value="pin" validate="checkPin"/> These properties are managed in the controller: app.controller("Ctrl", [&ap ...

What is the best way to display a single instance of a React component that is declared in multiple locations within the app?

Imagine I have 2 main components, A and B. Now, component C needs to be created inside both A and B. How can I guarantee that the same exact instance of C is generated in both places? Essentially, I want them to stay synchronized - any changes made to one ...

Can two Angular element components be utilized simultaneously on a single page in Angular 6?

Currently, I'm attempting to host independent Angular elements that can be seamlessly integrated into a non-Angular webpage. Everything works perfectly fine when there's only one element on the page, but as soon as I try to load two or more, I en ...

Maximizing Angular and Require's Potential with r.js

I'm facing some challenges while setting up r.js with require in my Angular application. As I am new to AMD, solving this issue might be a simple task for someone experienced. However, I need to maintain the current directory structure as it allows me ...

Storing data collected from a Google form into an Excel spreadsheet

I have created a form using table layout. My goal is to automatically shift the focus to the next input field once the current one reaches its maximum length. I tried implementing this functionality with jQuery, but it only seems to work with inputs and no ...

The update feature activates upon reaching the bottom of the page, but it continues to refresh constantly

In my VueJS component, I have implemented a scroll event that triggers an AJAX call to update the Jobs() function when the user is getting close to the end of the page. if ( windowScrollTop >= (documentHeight - windowHeight - 50) ) { this.updat ...

Determining the container height for every two-image row

I am currently working on a project for this website. My focus right now is on resizing vertical images using the following script: function Gallery(selector) { this.add_module = function (type, image) { var portrait_text = image.next('.portr ...

Working with React, with the choice of incorporating jsx or not

I am currently delving into the world of React and found myself able to run a simple app without using JSX. In my JavaScript file, I started with: class TestClass extends React.Component Do I really need to utilize JSX or can I just stick with JavaScript ...