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

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

CSS responsive grid - adding a horizontal separator between rows

I currently have a responsive layout featuring a grid of content blocks. For desktop view, each row consists of 4 blocks. When viewed on a tablet, each row displays 3 blocks. On mobile devices, each row showcases 2 blocks only. I am looking to add a ho ...

Exploring the parent of an HTML element / Finding a child element with unique content

Struggling with a challenge from frontendmentor that involves JavaScript. I need help on making the script detect if a P tag contains 0 as its content and then applying a different style to the containing div. <section class="pledge-box sub-section ...

"How to set the header in AngularJS when opening a new window with a GET request URL

Can anyone provide guidance on setting headers and opening a URL (https://www.example.com) in a new window without including sensitive authentication information in the URL parameters? I am working with AngularJS for this task. I have searched through exi ...

Retrieve JSON data from an external link and showcase it within a div, unfortunately encountering an issue with the functionality

Encountering the error message "XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access" Check out the plunker link for more information: http ...

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...

`replaceWith function limited to single use`

I'm encountering an issue where the replaceWith function is only working on the first instance. Even though I am getting updated data, it's not being written to the div after the initial replacement. $( "#searchboxform" ).keyup(function() { ...

Shifting a division using insertAfter

Hey there! I'm having a bit of trouble using the insertAfter function. In each product in my store, I need to position an "add to cart" button after the price. This is the code I tried: <Script type="text/javascript" > jQuery(document).read ...

Merge these two NPM packages together

Two npm projects exist: web-api (a library) and UI. The web-api utilizes gRPC-web to interact with the backend before converting it into a simple JavaScript object. In the UI, Vue.js is used in conjunction with web-api. Objective: merge these two project ...

Only trigger the onclick event once

Can anyone assist me with a function? The onclick event only triggers once. launchTagManager: function(id) { console.log(document.getElementById('metadata_field_multiple_text_701889_options['+id+']')); document.getElementById( ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

Copy password input field content in Vue to clipboard

I'm currently working on a Vue app that includes a form input for creating passwords. I've managed to implement a button that shows/hides the password, but I'm struggling with adding a copy to clipboard function. It doesn't seem to be w ...

Preventing Users from Uploading Anything Other than PDFs with Vue

I am currently working with Bootstrap-Vue and Vue2. Utilizing the Form File Input, I want to enable users to upload files, but specifically in PDF format. To achieve this, I have included accept="application/pdf": <b-form-file v-model=&quo ...

Utilize a date state variable in JSX Text based on a specific condition

My goal is to create a feature that allows users to pick a date using DateTimePickerModal. I want to display a clickable message that says "Select date" before any date is chosen, and then replace it with the selected date. While I am not certain if there ...

Preventing audio from being muted using JavaScript requires the removal of audio tags through a MutationObserver

I attempted to utilize the script below to eliminate all audio from a specific website: // ==UserScript== // @name addicto // @namespace nms // @include http://* // @include https://* // @version 1 // @grant none // ==/UserScrip ...

Tips for resolving issues with storing data in a text box that is constantly being added to

Can someone please assist me with this issue I'm facing? I am using isset to check if the index is defined, but it stores 0 instead of saving the value of the textbox. How should I tackle this problem? If I don't check if the index is defined and ...

Using Angular NgRx - triggering an action from an effect once certain actions yield a result

I'm encountering difficulties in dispatching actions that require results from five other actions (all listed in my effect). Could someone lend a hand? Essentially, I need to trigger an action within the effect only after these five actions have retu ...

If the input is marked as checked, apply a class to the corresponding HTML element

I need to manipulate the .form-group class by adding it if the nearest hotelObj element is checked, and removing it when hotelObj is unchecked. Instead of using addClass(), I prefer to utilize css(). $(".form-group").click(function() { if ($(this).ch ...

How can I access a method from another JavaScript file (service) in React JS's App.js to make API requests?

Just starting out with React js and trying to utilize REST API data. I've created a separate file named /shared/job-service.js for this purpose. My goal is to call a method from job-service.js in App.js and display the results on the UI. However, I&ap ...

Generating XML format from JSON using JavaScript

I am looking to create an XML format based on my JSON data, rather than converting it from JSON to XML. Here is an example of the JSON I want to convert to XML: var jsonData = { "Smart Shoes":{ "Product":"Smart Shoes", "Price":24.99, ...