How to Create a Timer in JavaScript and set time interval for next call?

JavaScript provides built-in timer functions:

  • ✅ setTimeout() – Run once after a delay
  • ✅ setInterval() – Run repeatedly at a fixed interval

setTimeout() – Single-Execution Timer

Executes a function once after a specified time.

Syntax
setTimeout(function, delayInMilliseconds);

Example
setTimeout(function () {
console.log("Executed after 3 seconds");
}, 3000);

📌 Use case:

  • Delay showing a message
  • Auto logout after inactivity
  • Redirect after success message

setInterval() – Repeating Timer

Executes a function continuously at a fixed interval.

Syntax
setInterval(function, intervalInMilliseconds);

Example
setInterval(function () {
console.log("Runs every 2 seconds");
}, 2000);

📌 Use case:

  • Refresh data
  • Poll API
  • Update clock / timer

How to Set Time Interval for the Next Call

Option 1: Using setInterval()
Best when the interval is fixed.
setInterval(fetchData, 5000);

function fetchData() {
console.log("API called every 5 seconds");
}

Option 2: Using Recursive setTimeout() (Recommended)
Best when you need dynamic control over the next execution.

function callApi() {
console.log("API called");
setTimeout(callApi, 3000);
}

callApi();

📌 Why use this?

  • Prevents overlapping calls
  • Waits for execution to finish
  • Ideal for API polling

Stop or Clear Timers

Stop setTimeout
let timerId = setTimeout(() => {
console.log("Will not execute");
}, 3000);

clearTimeout(timerId);

Stop setInterval
let intervalId = setInterval(() => {
console.log("Running...");
}, 2000);

clearInterval(intervalId);

Real-World Example: API Polling Every 5 Seconds

function pollServer() {
fetch('/api/status')
.then(response => response.json())
.then(data => {
console.log(data);
setTimeout(pollServer, 5000);
});
}

pollServer();

✔ Avoids duplicate calls
✔ Executes after response completes

Summary Table

MethodExecutesBest Use Case
setTimeoutOnceDelay action
setIntervalRepeatFixed interval
Recursive setTimeoutRepeatControlled interval

Interview Tip 💡

Prefer setTimeout recursion over setInterval for API calls to avoid overlapping executions.



How to count words in a string using JavaScript function?

Using split() and trim()

function countWords(str) {
    if (!str) return 0;

    return str.trim().split(/\s+/).length;
}

// Example
let text = "How to count words in JavaScript";
console.log(countWords(text)); // Output: 6

✔ Why this works

  • trim() removes leading/trailing spaces
  • \s+ handles multiple spaces, tabs, and new lines

Count Words Using Regular Expression (Advanced)

function countWords(str) {
    return (str.match(/\b\w+\b/g) || []).length;
}

✔ Use case

  • Accurate word detection
  • Ignores extra spaces

Count Words Without Using split()

function countWords(str) {
    let count = 0;
    let isWord = false;

    for (let char of str) {
        if (char !== ' ' && !isWord) {
            count++;
            isWord = true;
        } else if (char === ' ') {
            isWord = false;
        }
    }
    return count;
}

📌 Good for interviews to show logic skills.

Real-World Example (Textarea Word Counter)

<textarea id="text"></textarea>
<p>Word Count: <span id="count">0</span></p>

<script>
    document.getElementById("text").addEventListener("input", function () {
        let words = this.value.trim().split(/\s+/);
        document.getElementById("count").textContent =
            this.value.trim() === "" ? 0 : words.length;
    });
</script>

Handle Edge Cases

CaseInputOutput
Empty string""0
Extra spaces" Hello World "2
New lines"Hello\nWorld"2

Interview Tip 💡

Best approach:

str.trim().split(/\s+/).length

It’s simple, readable, and efficient.

Summary

  • ✔ Simple → split()
  • ✔ Accurate → Regex
  • ✔ Logical → Manual loop
  • ✔ UI-ready → Textarea example



How to Find Date Difference Between Two Dates Using JavaScript?

JavaScript provides the Date object, which allows easy calculation of differences between dates.

Date Difference in Days (Most Common)

function getDateDifferenceInDays(startDate, endDate) {
    const date1 = new Date(startDate);
    const date2 = new Date(endDate);

    const diffTime = Math.abs(date2 - date1);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    return diffDays;
}

// Example
console.log(getDateDifferenceInDays("2024-01-01", "2024-01-10")); // Output: 9

Date Difference in Hours, Minutes, and Seconds

function getDateDifference(date1, date2) {
    const diff = Math.abs(new Date(date2) - new Date(date1));

    return {
        days: Math.floor(diff / (1000 * 60 * 60 * 24)),
        hours: Math.floor(diff / (1000 * 60 * 60)),
        minutes: Math.floor(diff / (1000 * 60)),
        seconds: Math.floor(diff / 1000)
    };
}

Real-World Use Cases

  • ✔ Calculate number of days between dates
  • ✔ Project duration
  • ✔ Age calculation
  • ✔ Subscription expiry
  • ✔ Leave management systems

Important Notes

  • Always convert input to Date objects
  • Use Math.abs() to avoid negative values
  • Consider time zones when working with UTC dates