JavaScript code to alter the timeout duration for image changes: Update

I am working on a fun project that involves alternating between two images, one green and the other black. Here is the code snippet:

<script>
var switchImage = 1;
var delayTime = 500;

switchImages()
function switchImages() {
if (switchImage == 1) 
    {switchImage = 2; drawGreen();}
else {switchImage = 1; drawBlack();}
delayTime += 500;
setTimeout(switchImages(), delayTime)
}

function drawGreen() {
var canvas=document.getElementById("myCanvas");
var context=canvas.getContext("2d");
context.beginPath();
context.arc(438,398,125,0,2*Math.PI);
context.arc(838,398,125,0,2*Math.PI);
context.fillStyle="#00ff00";
context.fill();
}
function drawBlack() {
var canvas=document.getElementById("myCanvas");
var context=canvas.getContext("2d");
context.beginPath();
context.arc(438,398,128,0,2*Math.PI);
context.arc(838,398,128,0,2*Math.PI);
context.fillStyle="#000000";
context.fill();
}
</script> 

Adding an alert after incrementing the delay works fine, but I want it to happen automatically without clicking. Any suggestions would be greatly appreciated.

Answer №1

Your setTimeout function call needs a correction. Please remove the parentheses:

Check out the DEMO here

var wis = 1;
var delay = 500;
wissel()

function wissel() {
    if (wis == 1) {
        wis = 2;
        green();
    } else {
        wis = 1;
        black();
    }
    delay = delay + 500;
    setTimeout(wissel, delay)
}

function green() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.arc(438, 398, 125, 0, 2 * Math.PI);
    ctx.arc(838, 398, 125, 0, 2 * Math.PI);
    ctx.fillStyle = "#00ff00";
    ctx.fill();
}

function black() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.arc(438, 398, 128, 0, 2 * Math.PI);
    ctx.arc(838, 398, 128, 0, 2 * Math.PI);
    ctx.fillStyle = "#000000";
    ctx.fill();
}

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

Step-by-step guide on programmatically closing the Material-UI DropDownMenu

http://www.material-ui.com/#/components/dropdown-menu Having encountered a styling issue, I was compelled to rearrange the order of components within my material-ui DropdownMenu. Nevertheless, some buttons (renderNavLink) are now failing to close the Dro ...

The hovering event trail feature is not functioning in tsParticles, unlike in particlejs

I have two questions regarding the implementation of tsParticles in my React application. First question: <Particles id="tsparticles" options={{ background: { color: { value: "black&quo ...

What is the best way to add a new row to an existing CSV file using json2csv in Node.js?

I need to append a new row to an existing CSV file. If the CSV file already exists, I want to add the new row after the last existing row without adding a column header. Here is the code snippet that I have been using: var fields = ['total', &a ...

Merging Technology: Integrating Maps into Hybrid Applications

Currently, I am developing a mobile application using React-Native with a main focus on: Map Integration: Partial Success - I have successfully implemented all features mentioned in this link. The remaining task is to display live routing based on curren ...

Is it possible to prioritize loading JavaScript before images on a webpage?

My goal is to prioritize loading the js first and then the images for a specific reason. I want the blue rollover effect to be applied immediately upon loading. As the number of images on this page will eventually double, this could potentially become a la ...

Tips on successfully passing multiple keys and their associated HTML tag attributes in a React application

One of my links, specified with an a-tag, appears in this manner: <a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer"> {item.htmlReportText}</a> The values for the href and the linktext are sourced from the following: ro ...

Conditionally Add Columns to jQuery Datatables

I am working with a jQuery datatable to showcase data retrieved through an AJAX request. However, I am interested in adding a third column to the table specifically for administrators, allowing them to delete entries. Can someone guide me on how to incorpo ...

React Native not refreshing state data

I'm working with a FlatList that contains the code snippet below: <FlatList ........... refreshing={this.state.refresh} onRefresh={() => { this.setState({ ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...

When a user inputs in the field, it automatically loses focus

An error is encountered in two scenarios: When the input includes an onChange event handler When the input is located within a component that is called on another page For instance: In Page1.js, we have: return <div> <Page2 /> </div ...

Disregard earlier callback outcome if there has been a change in the state since then

I am facing an issue with my page that displays a list of countries retrieved from an external library. When I click on a country, it should show me all the cities in that specific country. Each country object has a provided method to fetch the list of c ...

Using React to trigger a child component's function upon clicking a tab

I need assistance with creating a React app that includes two tabs (Tab1, Tab2). When Tab2 is clicked, I want a message to appear in the console saying 'Function A is called'. Unfortunately, the code I have currently does not display the message ...

Rearrange lists by dragging and dropping them according to specific criteria

In my AngularJS project, I am utilizing the angular-drag-and-drop-lists library from here to create two lists with the following functionalities: Dragging items from list A to list B Dragging items from list B to list A Reordering items in list A Reorder ...

Import MDX metadata in Next.js on the fly

I am currently utilizing Next.js to create a static blog site. Following the guidelines in Next.js documentation, I set up @next/mdx and successfully imported MDX statically using import MDXArticle from "@/app/(article)/2023/test-article/page.mdx&quo ...

Searching for the index of a nested array in jQuery using JSON

I am currently working on developing an image uploader using Codeigniter3 along with jQuery and Ajax. Problem: I am facing difficulty in understanding how to locate the index of the array received from the ajax response shown below. Here is the data retu ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...

Decomposing a Vue.js API response into multiple variables

Utilizing vue to send http requests and store data in variables can be done like so: the api response will have the following structure: data: data: [id:1... etc] function: fetchOffers() { this.$http.get('http://127.0.0.1:8000/api/of ...

HTML table row content should be aligned to the left side

I am attempting to align the data in the 'Address' column without any margin. I want it to start from the left since it's overflowing. You can find the HTML, CSS, and JS code here Even though I tried using <td align="left">..</td& ...

Ways to eliminate excess space in a string using Robot Framework

My Variable : 54, 22 What I desire : 54,22 I attempted the following methods: Executing Javascript code var a = 54, 22;var x = a.split(' ').join('');return x and Executing Javascript code var a = 54, 22;var x = a.replace(/&bso ...

How can you enhance a component by including additional props alongside an existing onClick function?

As a newcomer to React and TypeScript, I've created a simple component that looks like this: const CloseButton = ({ onClick }: { onClick: MouseEventHandler }) => { const classes = useStyles(); return <CloseIcon className={classes.closeButto ...