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


How to set AM/PM in a textbox using JavaScript?

You can automatically format time and append AM/PM in a textbox using JavaScript.

1. Set Current Time with AM/PM in TextBox

2. Convert 24-Hour Time to AM/PM (User Input)

function convertToAmPm(time) {
    let [hours, minutes] = time.split(":");
    hours = parseInt(hours, 10);

    let ampm = hours >= 12 ? "PM" : "AM";
    hours = hours % 12 || 12;

    return hours + ":" + minutes + " " + ampm;
}

// Example
console.log(convertToAmPm("18:30")); // Output: 6:30 PM

3. Auto-Append AM/PM While Typing (Optional)

4. Common Use Cases

  • ✔ Time entry forms
  • ✔ Attendance systems
  • ✔ Scheduling applications
  • ✔ Booking systems


How do you consume Web Services in C# using .NET?

1️⃣ Consume REST Web Service in C# 

✅ Using HttpClient (Best Practice)

using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class ApiService
{
    private static readonly HttpClient client = new HttpClient();

    public async Task<string> GetDataAsync()
    {
        client.BaseAddress = new Uri("https://api.example.com/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync("users");

        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync();
        }
        return null;
    }
}

✔ Supports async/await

✔ High performance

✔ Used in .NET Core / .NET 6+

✅ Deserialize JSON Response

using Newtonsoft.Json;

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

var json = await api.GetDataAsync();
var users = JsonConvert.DeserializeObject<List<User>>(json);
// (You can also use System.Text.Json in .NET 6+)

2️⃣ POST Data to REST API

public async Task PostDataAsync()
{
    var data = new { Name = "John", Age = 30 };
    var content = new StringContent(
        JsonConvert.SerializeObject(data),
        Encoding.UTF8,
        "application/json");

    await client.PostAsync("users", content);
}

3️⃣ Consume SOAP Web Service in C# (Legacy Systems)

✅ Step-by-Step (Visual Studio)

  • Right-click project → Add Service Reference
  • Enter WSDL URL
  • Click Go → OK

Example Usage

ServiceReference1.MySoapClient client =
    new ServiceReference1.MySoapClient();

var result = client.GetEmployeeDetails(101);

✔ Automatically generates proxy classes

✔ Best for legacy enterprise apps

4️⃣ Consume Web Service Using WebClient (Old – Not Recommended)

using (WebClient wc = new WebClient())
{
    string data = wc.DownloadString("https://api.example.com/data");
}

⚠ Deprecated

⚠ Avoid in new projects

5️⃣ Handle Authentication (Bearer Token)

client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", "your_token_here");

6️⃣ Error Handling Best Practice

try
{
    var response = await client.GetAsync("users");
    response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex)
{
    Console.WriteLine(ex.Message);
}

🧠 Interview Comparison

TypeTechnologyUsage
RESTHttpClientModern apps
SOAPService ReferenceEnterprise legacy
Old RESTWebClientAvoid
JSONSystem.Text.JsonFast & lightweight

🚀 Best Practices (Important)

  • ✔ Reuse HttpClient
  • ✔ Use async/await
  • ✔ Handle timeouts
  • ✔ Secure API keys
  • ✔ Validate response


What is Cross Page Posting in ASP. NET?

Cross Page Posting

Cross Page Posting is a mechanism in ASP.NET that enables a Web Form to post its form data to a different page using the PostBackUrl property.

How Cross Page Posting Works

Page 1 – Source Page

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server"
    Text="Submit"
    PostBackUrl="~/Result.aspx" />

✔ The PostBackUrl specifies the target page.

Page 2 – Target Page

protected void Page_Load(object sender, EventArgs e)
{
    if (PreviousPage != null)
    {
        TextBox txtName =
            (TextBox)PreviousPage.FindControl("txtName");

        if (txtName != null)
        {
            string name = txtName.Text;
        }
    }
}

✔ PreviousPage gives access to the source page

✔ FindControl() fetches values from the previous page

Using @PreviousPageType (Strongly Typed – Recommended)

Page 2 (Result.aspx)

<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
protected void Page_Load(object sender, EventArgs e)
{
    string name = PreviousPage.txtName.Text;
}

✔ Type-safe

✔ Cleaner code

✔ Better performance

Difference: PostBack vs Cross Page Posting

FeaturePostBackCross Page Posting
Target pageSame pageDifferent page
Property usedDefault behaviorPostBackUrl
State handlingViewStatePreviousPage
Common useValidationMulti-page forms

When to Use Cross Page Posting

  • ✔ Multi-step forms
  • ✔ Wizard-style pages
  • ✔ Simple data transfer between pages
  • ✔ Avoiding Session usage

Limitations

  • ❌ Only works with ASP.NET Web Forms
  • ❌ Not recommended for large data transfer
  • ❌ Not supported in ASP.NET MVC / Core

Interview Tip

Cross Page Posting is an ASP.NET Web Forms feature that uses the PostBackUrl property to submit form data to another page, accessible via the PreviousPage object.


What is COALESCE and Why use in SQL Server?

Definition 

COALESCE evaluates its arguments from left to right and returns the first expression that is not NULL. If all expressions are NULL, it returns NULL.

Syntax

COALESCE(expression1, expression2, ..., expressionN)

Simple Example

SELECT COALESCE(NULL, NULL, 'SQL Server', 'Database');

Output: SQL Server

Practical Table Example

Table: Employees

EmpIdNameEmail
1Johnjohn@mail.com
2MaryNULL
3AlexNULL

Query:

SELECT 
    Name,
    COALESCE(Email, 'Not Available') AS Email
FROM Employees;

Result:

NameEmail
Johnjohn@mail.com
MaryNot Available
AlexNot Available

Multiple Column Example

SELECT COALESCE(HomePhone, WorkPhone, MobilePhone, 'No Contact') AS ContactNumber FROM Customers;

  • ✔ Returns first available phone number
  • ✔ Avoids NULL values

COALESCE vs ISNULL (Interview Tip)

FeatureCOALESCEISNULL
Standard SQL✅ Yes❌ No
Multiple values✅ Yes❌ No
Data type precedenceHigherFirst argument
PortabilityHighSQL Server only

One-Line Interview Answer

COALESCE is a SQL Server function that returns the first non-NULL value from a list of expressions.


What Are Generics in C#?

Technical Definition 

Generics allow developers to create strongly typed components by specifying type parameters that are replaced with actual data types at compile time.

Why Generics Are Needed

Before generics, collections stored data as object, which caused:

  • Runtime casting errors
  • Boxing and unboxing overhead
  • Poor type safety

Generics solve these problems.

Simple Example (Generic Class)

public class MyGeneric<T>
{
    public T Data { get; set; }
}
MyGeneric<int> obj1 = new MyGeneric<int>();
obj1.Data = 100;

MyGeneric<string> obj2 = new MyGeneric<string>();
obj2.Data = "Hello";
  • ✔ Compile-time type checking
  • ✔ No casting required

Generic Method Example

public void Print<T>(T value)
{
    Console.WriteLine(value);
}
Print<int>(10);
Print<string>("C# Generics");

Generic Collection Example

List<int> numbers = new List<int> { 1, 2, 3 };
List<string> names = new List<string> { "John", "Alex" };
  • ✔ Type safe
  • ✔ Faster than non-generic collections

Generic Constraints

public class Repository<T> where T : class
{
}

Common Constraints

ConstraintDescription
where T : classReference type
where T : structValue type
where T : new()Default constructor
where T : BaseClassInheritance
where T : interfaceInterface implementation

Advantages of Generics

  • ✔ Strong type safety
  • ✔ Reusable code
  • ✔ Better performance
  • ✔ Cleaner, maintainable code

One-Line Interview Answer

Generics in C# allow the creation of type-safe and reusable code by defining placeholders for data types that are specified at runtime or compile time.


What is the difference between STUFF and REPLACE in SQL Server?

SQL Server String Functions

In SQL Server, both STUFF and REPLACE are string functions used to modify text, but they work in very different ways.

1. STUFF Function

Purpose: Deletes a specified number of characters from a string starting at a given position and optionally inserts another string at that position.

Syntax: STUFF(string, start, length, replace_with)

Example:

SELECT STUFF('SQLServer', 4, 6, ' Database');

Output: SQL Database

  • ✔ Position-based
  • ✔ Allows deletion + insertion

2. REPLACE Function

Purpose: Replaces all occurrences of a specified substring with another substring.

Syntax: REPLACE(string, search_string, replace_string)

Example:

SELECT REPLACE('SQL Server Server', 'Server', 'Database');

Output: SQL Database Database

  • ✔ Value-based
  • ✔ Replaces every match

Key Differences

FeatureSTUFFREPLACE
Replacement typePosition-basedText-based
ReplacesFixed charactersAll matching substrings
Occurrence controlSingle locationAll occurrences
Uses indexYes (start position)No
Common useInsert/remove textFind & replace

Real-World Example

Remove First Comma Only (STUFF):

SELECT STUFF(',,100,200', 1, 1, '');

Output: ,100,200

Replace All Commas (REPLACE):

SELECT REPLACE(',,100,200', ',', '');

Output: 100200

🧠 Interview One-Liner

STUFF modifies a string based on character position, whereas REPLACE substitutes all occurrences of a specified substring.