Categories
JavaScript Answers

How to Create a Stopwatch Using JavaScript?

Sometimes, we want to create a stopwatch using JavaScript.

In this article, we’ll look at how to create a stopwatch using JavaScript.

Create a Stopwatch Using JavaScript

To create a stopwatch using JavaScript, we can add the HTML and JavaScript code for the timer display and the buttons to start, stop and reset the timer.

For instance, we write:

<h1>
  <span id="hour">00</span> :
  <span id="min">00</span> :
  <span id="sec">00</span> :
  <span id="millisec">00</span>
</h1>

<button onclick="startStop()" id="start">Start</button>
<button onclick="reset()">Reset</button>

to add the HTML code for the stopwatch timer display and the buttons to control the stopwatch.

Then we write:

let x;
let startstop = 0;


const start = () => {
  x = setInterval(timer, 10);
} /* Start */

const stop = () => {
  clearInterval(x);
}

let millisec = 0;
let sec = 0;
let min = 0;
let hour = 0;
let miliSecOut = 0;
let secOut = 0;
let minOut = 0;
let hourOut = 0;

const checkTime = (i) => {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

const timer = () => {
  milliSecOut = checkTime(millisec);
  secOut = checkTime(sec);
  minOut = checkTime(min);
  hourOut = checkTime(hour);

  millisec = ++millisec ;

  if (millisec  === 100) {
    millisec = 0;
    sec = ++sec;
  }

  if (sec == 60) {
    min = ++min;
    sec = 0;
  }

  if (min == 60) {
    min = 0;
    hour = ++hour;

  }


  document.getElementById("millisec").innerHTML = milliSecOut;
  document.getElementById("sec").innerHTML = secOut;
  document.getElementById("min").innerHTML = minOut;
  document.getElementById("hour").innerHTML = hourOut;

}


const reset = () => {
  millisec = 0;
  sec = 0;
  min = 0
  hour = 0;

  document.getElementById("millisec").innerHTML = "00";
  document.getElementById("sec").innerHTML = "00";
  document.getElementById("min").innerHTML = "00";
  document.getElementById("hour").innerHTML = "00";
}


const startStop = () => {
  startstop = startstop + 1;

  if (startstop === 1) {
    start();
    document.getElementById("start").innerHTML = "Stop";
  } else if (startstop === 2) {
    document.getElementById("start").innerHTML = "Start";
    startstop = 0;
    stop();
  }
}


We define x to store the timer for updating the stopwatch time count.

startstop stores the stopwatch toggle state.

Then we create the start function that calls setInterval that calls the timer function every 10 milliseconds to run the timer.

The stop function calls clearInterval to stop the timer.

Next, we define variables to store the elapsed time.

In the timer function, we call checkTime to prepend a 0 before i if i is less than 10 and return that result.

We call that for all time variables in the timer function.

Then we update the millisec variable to update the elapsed time in milliseconds.

Next, we update the millisec, sec, and min variables to update the milliseconds, seconds and minutes parts of the elapsed time respectively.

Then we update the display of the stopwatch by setting the innerHTML property of all the elements.

After that, we define the reset function to reset all the values to 0 and update the corresponding elements.

Next, we create the startStop function to toggle the timer on and off.

If it’s 1, we start the timer by calling the start function.

And we update the start button to show Stop.

If it’s 2, then we update the start button to show Start and we call stop to stop the timer.

And we also reset the startstop state to 0.

startStop and reset are called when we click the Start/Stop and Reset buttons respectively.

Conclusion

To create a stopwatch using JavaScript, we can add the HTML and JavaScript code for the timer display and the buttons to start, stop and reset the timer.

Categories
JavaScript Answers

How to Split a String Only the at the First n Occurrences of a Delimiter?

Sometimes, we want to split a string only the at the first n occurrences of a delimiter.

In this article, we’ll look at how to split a string only the at the first n occurrences of a delimiter.

Split a String Only the at the First n Occurrences of a Delimiter

To split a string only the at the first n occurrences of a delimiter, we can use the split method with the JavaScript array’s splice and join methods.

For instance, we write:

const string = 'Split this, but not this'
const arr = string.split(' ')
const result = arr.splice(0, 2)

result.push(arr.join(' '));
console.log(result)

We call split on the whole string.

Then we call splice to with 0 and 2 to get the first 2 items from the arr array and assign it to result.

The items returned by splice are removed from arr.

Next, we call arr.join with the remaining substrings in the arr array with a space to join them together.

Finally, we call result.push on that string to add that string to result.

Therefore, result is ['Split', 'this,', 'but not this'] according to the console log.

Conclusion

To split a string only the at the first n occurrences of a delimiter, we can use the split method with the JavaScript array’s splice and join methods.

Categories
JavaScript Answers

How to Mask a US Phone Number String with JavaScript?

Sometimes, we want to mask a US phone number string with JavaScript.

In this article, we’ll look at how to Mask a US phone number string with JavaScript.

Mask a US Phone Number String with JavaScript

To Mask a US phone number string with JavaScript, we can match the different parts of the phone number with a regex that has capturing groups.

For instance, we write:

<input type="text" id="phone" placeholder="(555) 555-5555" />

to add the input.

Then we write:

document.getElementById('phone').addEventListener('blur', (e) => {
  const x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
  e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});

to select the phone input with document.getElementById('phone').

Then we call addEventListener with 'blur' to listen to the blur event.

The blur event is emitted when we move focus out of the input.

In the event handler, we call replace on the input value to replace all non digit substrings with empty strings.

Then we call match to match the digit groups of a phone number.

Then we set the e.target.value to the phone number with the parentheses and dashes.

x has the digit groups.

Now when we type in a phone number, we should see the parentheses and dashes added to the groups.

Conclusion

To Mask a US phone number string with JavaScript, we can match the different parts of the phone number with a regex that has capturing groups.

Categories
JavaScript Answers

How to Check if a JavaScript Array Contains Duplicate Values?

Sometimes, we want to check if a JavaScript array contains duplicate values.

In this article, we’ll look at how to check if a JavaScript array contains duplicate values.

Check if a JavaScript Array Contains Duplicate Values

To check if a JavaScript array contains duplicate values, we can use the JavaScript array some and indexOf methods.

For instance, we write:

const arr = [11, 22, 11, 22];
const hasDuplicate = arr.some((val, i) => arr.indexOf(val) !== i);
console.log(hasDuplicate)

to check if arr has duplicate values.

We call some with a callback to check if some array entries matches the condition returned by the callback.

indexOf returns the index of the first element that matches a given value.

So if indexOf returns a value that isn’t equal to the index i, we know that the value is a duplicate.

Therefore, the console log should log true.

Conclusion

To check if a JavaScript array contains duplicate values, we can use the JavaScript array some and indexOf methods.

Categories
JavaScript Answers

How to Add Hover CSS Attributes Via jQuery and JavaScript?

Sometimes, we want to add hover CSS attributes via jQuery and JavaScript.

In this article, we’ll look at how to add hover CSS attributes via jQuery and JavaScript.

Add Hover CSS Attributes Via jQuery and JavaScript

To add hover CSS attributes via jQuery and JavaScript, we can call the jQuery mouseenter and mouseleave methods on the selected element.

For instance, if we have:

<div id='some-content'>
  hello world
</div>

Then we write:

$("#some-content")
  .mouseenter(function() {
    $(this).css("background", "#F00").css("border-radius", "3px");
  }).mouseleave(function() {
    $(this).css("background", "").css("border-radius", "0px");
  });

We select the div with:

$("#some-content")

Then we call mouseenter with a callback that calls css to set the background and border radius on the div when our mouse enters the div.

Likewise, we call mouseleave with a callback that calls css to set the background and border radius on the div when our mouse leaves the div.

Now when we move our mouse in and out of the div, we see different styles applied to the div.

Conclusion

To add hover CSS attributes via jQuery and JavaScript, we can call the jQuery mouseenter and mouseleave methods on the selected element.