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

Error: The PDFJS variable is not recognized when trying to load a PDF file

I've been experimenting with pdf.js to load PDFs into a web application in order to extract information in real-time. However, I keep encountering an error even with a simple example. I've attempted enclosing the code in $(document).ready() as a ...

Exploring the World of Metaprogramming with AngularJS Filters

Can we generate filters dynamically in Angular? Below are some basic filters that extract specific properties from an array of objects. module.filter("firstAndLastName", function() { return function(input) { return input.map(function(obj) { ...

Flipping numbers in Arabic font using PDF kit

Currently, I am utilizing the pdfkit library in my Node.js application for PDF generation. However, I encountered an issue while attempting to incorporate Arabic text. The problem lies in the fact that it consistently rearranges the numbers within Arabic t ...

Make sure to update the package.json file at multiple locations following the execution of the "npm i" command

My goal is to automatically detect any newly installed packages based on my package.json file. This way, whenever I run "npm i", the new package will be added not only to the usual "dependencies" section but also to a custom section called "extDependenci ...

Array of generic types in Typescript

Here's a method that I have: getFiveObjectsFromArray(array: T[]) { return array.slice(0, 5); } I've been using this method multiple times. Is there a way in TypeScript to pass a generic argument instead of using multiple types? Also, when ...

Can the ValidationPipe be utilized with a whiteList on the response body?

How can we prevent the return of certain key values in responses from a NestJs server when using TypeOrm entities? For instance, ensuring that a user's password is never sent to any client: In the user.entity.ts file: @Entity() export class User ext ...

Elevation in design ui component

I am having an issue with the height of a theme-ui component I embedded. Even though the console shows it correctly, it is displaying at 100% height. <Embed src={url} sx={{width: '800px', height: '400px'}}/> This embed is contain ...

Performing an asynchronous POST request in JavaScript

Hey there, I successfully managed to implement a post request using ajax for my submit functionality. However, I am now looking to make this asynchronous to account for any delays in processing by my php file. Unfortunately, I am struggling to figure out h ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

Building upon the preceding inquiry, a ReferenceError has occurred due to the object being undefined

After researching online, I came across a similar question marked as a duplicate that brought me to this link: How do I return the response from an asynchronous call?. Even though I couldn't find a solution in that thread, it seems like I may need to ...

Acquire user input using AngularJS

Is it possible to retrieve the value of an input text using AngularJS without utilizing a Controller? If so, what approach would achieve this? I have come across some resources discussing similar queries, but they all involve .controller here is one such ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Creating an interactive time selection tool with two dropdown lists that are dependent on each other using HTML and JavaScript

Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...

Difficulty encountered when trying to template routes with more than one slash in Angular-route

I'm encountering difficulties with my Express+Jade+AngularJS[v1.2.22] application when attempting to access routes such as "mydomain.com/something/somethingelse" or "mydomain.com/something/another/last", which include one or more path subdivisions. T ...

Troubleshooting a Problem with the Horizontal Scrollbar in Dynamic jqGrid

Currently, I am working on an ASP.net MVC project where I have implemented both dynamic and static jq grids. However, I am encountering an issue with the horizontal scroll bar in my application. To address this problem, I attempted to modify the overflow ...

Is incorporating re-routing into an action a beneficial approach?

My main concern involves action design strategies: determining the best timing and method for invoking actions. In my project using Mantra (utilizing React for the front-end and Meteor's FlowRouter for routing), there is a UI component that includes ...

`The resurgence of CERT_FindUserCertByUsage function in JavaScript`

I am currently grappling with unraveling the connection between C++ dlls and JavaScript. There is a snippet of js code that reads: cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null); where the variable cert is ini ...

Is it possible to generate AMP pages using React server-side?

After experimenting with rendering the AMP page by generating HTML on the server using React, I have successfully created a component that fetches data from the API and renders the necessary amp tags. The component is responsible for producing a plain HT ...

I am looking to enhance the readability of my asynchronous function calls

At the moment, I am handling my Promises by calling an async function and then chaining it with .then(). But I feel like there could be a more readable approach. This is how it currently works: const fetchData = async() => { const response = await ax ...

Utilizing CSS for styling a class with a dynamic name

On the server side, I am dynamically generating class names like this: <p class="level_1">List item 1</p> <p class="level_2">List item 2</p> <p class="level_3">List item 3</p> <p class="level_1">List item 1</p& ...