The callback function in a JavaScript setTimeout() loop does not execute properly once the loop has completed

I've been facing a challenge in my recent JavaScript project. I've created two animations named DarkWaves and clearScreen. My goal is to pass a function (such as clearScreen) to DarkWaves, let it run its animation, and then execute the passed function. However, I'm struggling to make this work. Upon testing, I discovered that using setTimeout in the code causes an error - callback is not recognized as a function. Even when I checked the typeof callback, it only returned 'defined' unless placed inside a function without setTimeout. To provide more context, I'll include the relevant parts of the code below:


function DarkWaves(callback){//Dark Wave!

function advancingTriangle(whereToGo, rbgValuez){
    //drawing logic here
}

if(waveCount === 0){
    $('#rightSideBarOuter').hide();//Clearing HTML elements for wave movement
    $('#mainAreaOuter').hide();
}

//conditional statements for drawing triangles at different stages of animation

waveCount++;

if(waveCount > 120) waveCount = 0;

if(waveCount !== 0) setTimeout(DarkWaves, 50);
else {callback();}
}

To workaround the issue, I implemented a temporary solution that delays the execution of the desired function after 6500 seconds following the completion of DarkWaves. Any advice or assistance would be greatly appreciated!

Answer №1

After a call to setTimeout(DarkWaves, 50);
, the callback is not passed along to the next invocation of DarkWaves, leading to the loss of the callback.

To address this issue, you should explicitly pass the callback like this:

setTimeout(function() { DarkWaves(callback); }, 50);

For example:

if (waveCount !== 0) {
    setTimeout(function() { DarkWaves(callback); }, 50);
} else{
    callback();
}

Alternatively, you can use Function#bind:

if (waveCount !== 0) {
    setTimeout(DarkWaves.bind(this, callback), 50);
} else{
    callback();
}

This approach is slightly more lightweight in comparison.

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

Enhancing data management with Vuex and Firebase database integration

Within my app, I am utilizing Firebase alongside Vuex. One particular action in Vuex looks like this: async deleteTodo({ commit }, id) { await fbs.database().ref(`/todolist/${store.state.auth.userId}/${id}`) .remove() .then ...

Transferring data between various stages of the user interface

As a newcomer to angularJs, I find myself facing an issue with two forms existing in different UI states (URLs) labeled as Step 1 and Step 2. The process requires filling up Step 1 and moving to the next step by clicking the NEXT button, which then leads t ...

React Native ScrollView ref issue resolved successfully

I'm trying to automatically scroll to the bottom of a flatlist, so here's what I have: const scrollViewRef = useRef(); //my scroll view <ScrollView ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scr ...

Ending a session in Node.js with Express and Socket.io

I've been grappling with this issue for a few days now and I'm just not able to wrap my head around it. I need to end my session when I navigate away from the webpage, but the error message I keep receiving (which ultimately crashes the server) r ...

Switching from using v-data-table to v-virtual-scroll

I am currently in the process of switching from using v-data-table to v-virtual-scroll, but I am struggling to determine the correct syntax for the virtual scroller. Can you assist me with this, please? I want to maintain the same display as before, but no ...

Is there a way to trigger a fabric.js event externally?

Is there a way to trigger a fabric.js event externally? For example, if I have a 3D model that tracks the mouse's position and provides the UV coordinates on the canvas, I want to be able to emit click, mousemove, and mouseup events. Currently, everyt ...

Experiencing an unusual issue with grunt: The Gruntfile.js seems to be missing the 'flatten' method

Encountering an unusual error message while attempting to run grunt stated: TypeError: Object Gruntfile.js has no method 'flatten' Being a beginner with node.js, npm, and grunt, I believe my installation of node, npm, and grunt was done correctl ...

Integrating CSS with Material-UI in a React project: A step-by-step guide

I am currently developing a project using React (along with TypeScript) and the Material-UI library. One of my requirements is to implement an animated submit button, while replacing the default one provided by the library. After some research, I came acr ...

Reactjs Invariant Violation caused by the npm package (react-loader)

I'm currently attempting to integrate react-loader into my react component. This is the code snippet I'm using: /** @jsx React.DOM */ var Loader = require('react-loader'); var DisplayController = React.createClass({ // etc ...

Prevent PHP Timer from resetting each time the page is refreshed

I am struggling with implementing a timer for my Quiz web application. The timer keeps resetting every time the user moves to the next question or refreshes the page. I attempted to save the remaining time to a variable, but as a beginner, I'm not su ...

Adjust the tooltip image alignment to be offset from the cursor and appear at the bottom of the page

After creating a code snippet for image tooltips on text hover, I encountered an issue on my website where the bottom of the page expanded to accommodate the images. Is there a simple way to align the cursor at the bottom of the image when scrolling to the ...

Continuous updates triggered by mouse movement with jQuery

Can someone help me figure out why my custom description isn't following my mouse pointer during the 'mousemove' event on an image? I've provided the HTML code below: <!DOCTYPE html> <html lang="en> <head> ...

Investigating Jquery Flip Card Issues

Looking to create a set of flip cards using HTML, CSS, and jQuery. Currently facing an issue where only the first card is flipping when clicked. Any suggestions on how to modify the jQuery code to make it work for all cards would be highly appreciated. C ...

Prevent sticky div from overlapping with footer

I currently have a social link menu that is fixed to the left side of my page, structured like this: <footer id="colophon"></footer> <div> <nav> <ul id="social"> <li>Link1</li> ...

Adapting the position of a table row in AngularJS based on the

I need assistance with creating a dynamic table-row that moves to indicate the current time in a table filled with timestamps. <table> <tr ng-repeat="timestamp in timestampArray"> <td>{{timestamp}}</td> </tr> ...

What are some effective ways to test React Router using Jest?

Just starting out with Jest testing and looking to test the code below. import React from "react"; import "./ButtonLogin.css"; import { Link } from 'react-router-dom'; function ButtonLogin() { return ( <Link to ...

How can I tally the frequency of characters in a given string using Javascript and output them as numerical values?

I am in the process of tallying the frequency of each individual character within a given string and representing them as numbers. For example, let's consider the string "HelloWorld". HELLOWORLD There is one H - so 1 should be displayed with H remov ...

Tips for determining what elements are being updated in terms of style

I need assistance with modifying the functionality of a webpage's dropdown menu. Currently, it displays when the mouse hovers over it, but I want to change it to appear on click using my own JavaScript. Despite setting the onmouseout and onmouseover e ...

The button click event fails to trigger after entering text into an input field

I created a basic calculator. Users can input a value in the designated field and then click on the '+' button. The cursor stays in the input field, allowing users to immediately enter a new value after clicking the '+'. The mouse poi ...

Issues with displaying AngularJs directive template

Having an issue with my AngularJs directive. Everything works perfectly fine when I use the "template" attribute, but when I switch to using "templateURL", it stops working. Both the JavaScript file for the directive and the HTML file for the template are ...