Javascript dual stopwatch

Looking for a way to use vanilla JavaScript to display alternating text screens - one set of messages for 30-40 seconds, followed by another set for 10 seconds. For example, cycling through messages like "hello", "world", "I love java script". Trying to achieve this with an array and timers but struggling to make the transition happen smoothly between 30 and 10-second intervals. Instead of doing the math manually, I'd like a cleaner solution. Following an example from W3Schools but seeking a more concise method.

Current approach:

function timedText() {
    setTimeout(myTimeout1, 10000) 
    setTimeout(myTimeout2, 30000) 
    setTimeout(myTimeout3, 40000)
}

function myTimeout1() {
    document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: yellow; color: black; text-align: center;'>Mountain Climbers</h2>";
}

function myTimeout2() {
    document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: red; color: white; text-align: center;'>REST</h2>";
}

function myTimeout3() {
    document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: yellow; color: black; text-align: center;'>Inch Worms</h2>";
}

Answer №1

Is it possible to simplify this by creating two functions that call each other?

function firstFunction() {
  window.alert('Message One')
  setTimeout(secondFunction, 10*1000);
}

function secondFunction() {
  window.alert('Message Two');
  setTimeout(firstFunction, 30*1000);
}

setTimeout(secondFunction, 30*1000);

You can customize the window.alert calls with your preferred method for displaying text.

EDIT Upon request, here is an approach to cycle through an array of words at different intervals using the following HTML:

<div id='msgBox'></div>

Create an array and a function to display the words from the array like so:

var msgBox = document.getElementById('msgBox');
var messages = ['hello', 'world', 'i' ,'love', 'java', 'script']

function updateMessage() {
  var msg = messages.shift();
  msgBox.innerHTML = msg;
  var duration = messages.length % 2 ? 10 * 1000 : 30 * 1000
  setTimeout(updateMessage, duration)
}

setTimeout(updateMessage, 10*1000)

You can adjust the duration logic as needed, such as setting specific time intervals for even or odd array lengths.

If you want to include additional information in the inner content (e.g., varying styles within an h2 tag), you can modify the array elements accordingly or implement logic similar to the duration calculation for selecting the appropriate styling.

Here's the fiddle

Answer №2

If you want to make some changes, try this method!

You have the option to adjust the timeout interval based on your needs

function myFunction1() {
    document.getElementById("demo").innerHTML = "<h2 style='background-color: yellow; color: black; text-align: center;'>Sunshine</h2>";
    setTimeout(myFunction2,3000);
}

function myFunction2() {
    document.getElementById("demo").innerHTML = "<h2 style='background-color: red; color: white; text-align: center;'>Cloudy</h2>";
    setTimeout(myFunction3,5000);
}

function myFunction3() {
    document.getElementById("demo").innerHTML = "<h2 style='background-color: yellow; color: black; text-align: center;'>Rainy</h2>";
    setTimeout(myFunction1,2000);
}
myFunction1();
<div id="demo">
</div>

Answer №3

Implementing OOP for efficient timer functionality.

function Timer(fn, delay) {
  this.startTimer = function(fn, delay) {
    setTimeout(fn, delay);
  }
  return this;
}

function timedText() {
  let timer1 = new Timer();
  let timer2 = new Timer();
  let timer3 = new Timer();
  timer1.startTimer(myTimeout1, 1000);
  timer2.startTimer(myTimeout2, 3000);
  timer2.startTimer(myTimeout3, 4000);
}

function myTimeout1() {
  document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: yellow; color: black; text-align: center;'>Mountin Climbers</h2>";
}

function myTimeout2() {
  document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: red; color: white; text-align: center;'>REST</h2>";
}

function myTimeout3() {
  document.getElementById("tebatademo").innerHTML = "<h2 style='background-color: yellow; color: black; text-align: center;'>Inch Worms</h2>";
}

timedText();
<div id="tebatademo"></div>

Easily adaptable for future timer functionalities with OOP approach.

Feel free to expand or modify the timer as needed in the future.

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

Combining Two Validation Methods for jQuery Validate Plugin

Seeking advice on how to incorporate custom validation methods from jQuery validate into another method for validating data. Specifically, I have a 'Document ID' field that can accept either CPF or CNPJ (Brazilian documents) and I need to validat ...

Add and alter a script tag within the Vue template

I am currently working on integrating a payment service into my platform. The payment service has provided me with a form that includes a script tag. This question is a follow-up to a previous query on inserting a script tag inside a Vue template. Here i ...

Seeking assistance in configuring a dynamic payment amount feature on Stripe using Node.js

As a newcomer to node and javascript, I'm seeking guidance on how to proceed with the code below. I have copied it from the Stripe documentation, but I am unsure about the function for the commented token. Initially, everything was working fine with t ...

What is preventing the final question from appearing in the mapping function and not being included in the score calculation in (react/chart.js)?

I've encountered a problem with an array of questions. There are 24 questions in the array, but for some reason, the last question is not being displayed and included in the final score. I'm puzzled as to why it only renders 23 times. My initial ...

Utilize an enum from a shared library by exporting it and incorporating it into a TypeScript project

Currently, I am in the process of developing a library where a React component is being exported along with some interfaces and an enum. After compiling the typescript project, I realized that the library is specifically for React and not typescript, so I ...

Tips for using JavaScript to magnify a specific point on a webpage

As I work on my web project, I am trying to achieve the functionality of zooming in a div element centered around the mouse position while using the mouse wheel. I came across a helpful answer by @Tatarize on Zoom in on a point (using scale and translate), ...

Understanding the difference between emitting and listening with socket.io-stream

The socket.io-stream documentation includes an interesting example for transferring streaming data: // sending data ss(socket).on('file', function(stream) { fs.createReadStream('/path/to/file').pipe(stream); }); // receiving data ss ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

Combining two arrays using conditions in Lodash

I have two different arrays as shown below: const firstArray = [{name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "4"}]; const secondArray = [{name: "1"}, {name: "5"}, {name: &q ...

The firebase Function did not return a valid response, it was expecting a Promise or

Hello, I have been working on some code to send friend request notifications from one Android app to another. Unfortunately, I am encountering an error that says "Function returned undefined, expected Promise or value" in the functions console. Additionall ...

React JS - Sending props from Dev and Build to App component

Looking to include static assets and props in my App, specifically having image assets set with a base64 string in the build process. Want to ensure these assets are accessible to the App's props before development and build stages, similar to the fun ...

Automatically collapse the Shadcn-UI Accordion when the mouse exits

For my self-education project, I am working on building a sidebar with an accordion using Shadcn-ui, NextJS (13.4), React, and Node. Being new to these technologies, I have encountered a problem that I can't seem to solve. The sidebar expands on mous ...

Issue with unapplied nullable type during export操作

I'm struggling to understand why my nullable type isn't being applied properly Here's an illustration interface Book { name: string; author: string; reference: string; category: string; } async function handleFetch<T>(endpoin ...

Loading an image into a Three.js scene

Attempting to display an image in my 360-degree scene, but encountering issues with the code: <script> var controls, camera, scene, renderer, element; var container; var sceneCube; init(); animate(); function init() { // CAMERAS camera ...

Is Accessing Elements Truly Constant Time Complexity O(1)?

Some say that accessing an element in an array is an example of a O(1) operation. According to a particular source, O(1) can be defined as follows: [Big-O of 1] means that the execution time of the algorithm does not depend on the size of the input. I ...

On top of the world always is Mesh or Sean

Currently I am working on a 3D diagram, possibly using a bar or line graph. I have been using three.js version 60 as most of my code has already been developed with this version. However, I am facing an issue with adding legends to the diagram. The 3D obje ...

Is there a similar concept to Django mixins in Node.js?

Having previously worked with Django and now transitioning to Node, I am familiar with Mixins that can be added to enforce specific authorization rules on models, like allowing only logged-in users to view certain content or restricting editing rights to ...

Tips for querying nested arrays of objects in MongoDB aggregation pipeline

After going through several stages of pipeline processing, I now have a document structured like this: [ { "_id": ObjectId("5e9d5785e4c8343bb2b455cc"), "name": "Jenny Adams", "report": [ ...

"Presenting Invoice Information on an Invoice Template: A Step-by-Step Guide

Currently, I am working with Laravel 5.7 and VueJs 2.5.*, where I have a table of invoices. My goal is to create a new component that will display a specific invoice based on user selection, allowing them to view or print the chosen invoice. I am still ex ...

What is the best way to arrange an array to display country data based on Covid cases in descending order rather than alphabetical order?

This particular code snippet retrieves Covid19 statistics data using an API. Currently, it displays the data for covid cases of all countries in Alphabetical order. However, I am looking to present the data in descending order, meaning that the country wit ...