The setInterval example provided in the Javascript Mozilla documentation does not seem to be functioning properly on JSFiddle

I referred to Example #2 in the Mozilla docs about setInterval() (https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval?redirectlocale=en-US&redirectslug=DOM%2Fwindow.setInterval#Example_1.3A_Generic) in my JSFiddle but the text color does not alternate between red and blue as expected:

DEMO: http://jsfiddle.net/lpsternotes/JHpt9/

Could it be due to a requirement for jQuery or a markup issue, even though I copied the code exactly as is?

I would also like to clarify: is the reason var nIntervId; is declared as a global variable at the beginning so that it can be accessed by both the changeColor() and stopTextColor() functions?

var nIntervId; //global variable

function changeColor() {
  nIntervId = setInterval(flashText, 500);
 }

function flashText() {
  var oElem = document.getElementById("my_box");
  oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}

function stopTextColor() {
  clearInterval(nIntervId);
}

In other words, if the code were written like this:

function changeColor() {
  var nIntervId = setInterval(flashText, 500);
}

function flashText() {
  var oElem = document.getElementById("my_box");
  oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
}

function stopTextColor() {
  clearInterval(nIntervId); //would this lead to an undefined variable??
}

Answer №1

The functions you've created are enclosed within another function that is executed when the page loads (as indicated by the second drop-down menu in the JSFiddle options on the left).

Due to this setup, the functions are limited in scope to that specific function and are not considered global.

As a result, they cannot be accessed by the onload="stopTextColor();" attribute.

To resolve this issue, simply include the stopTextColor() function call within your existing onload handler instead of creating a separate one with the onload attribute.

Answer №2

Your code snippet is functioning properly. To enhance its performance, consider modifying the second dropdown menu on the left from "onLoad" to "No Wrap - in Head."

For further insights, refer to this resource to understand the rationale behind this adjustment.

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

Struggling to iterate through the children of a variable with the help of express-handlebars?

Currently, I am in the process of developing an application using Javascript along with express, express-handlebars, and MySQL. One of my main tasks is to establish a route that follows the pattern '/viewowner/:ID/scoreboards/:year' where ID sig ...

Fetching data from database and populating dropdown menu through Struts 2 action class with the assistance of jtable

Utilizing the jtable jQuery plugin (http://jtable.org/) in my current project has been a game-changer. It allows for the creation of AJAX based CRUD tables without the need to code HTML or JavaScript. For more details, refer to this image: The jtable cod ...

Center the image within the div by setting its position to absolute

<div class='img-box'> <img /> //position absolute <img /> //position absolute <img /> //position absolute <img /> //position absolute I am struggling to center the images within this div because of their absolute p ...

Ensure that text is aligned alongside an image only when both elements are enclosed within <p> tags

When using an API to pull markdown content from Contentful and converting it to HTML with ReactMarkdown, a common issue arises. The resulting HTML structure often places the text content in separate paragraphs such as: <p>Some text content</p> ...

Using AJAX to create an interactive dropdown menu with changing options

I have been working on creating a dropdown menu using Ajax. When hovering over the navigation bar, the menu successfully triggers the Ajax function to display the dropdown options. The issue arises when attempting to navigate to another page (show_activi ...

Unexpected behavior exhibited by DOM elements

I can't seem to figure out this issue. Every time I run this loop: for ( var i=0; i < 10; i++ ) { var $items = $(balls()); console.log($items); $container.imagesLoaded(function(){ $container.append( $items ).masonry( 'app ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

Are programmatic clicks distinguishable from manual clicks in JQuery?

Currently, I am in the process of creating selectable and draggable elements for a table. You can test the functionality by following this JsFiddle link (please try vertically selecting). Initially, the selection works well but upon trying to select for th ...

Should one consider using requirejs to enhance individual pages instead of relying solely on vanilla JavaScript applications?

I have a question regarding the practical use of RequireJS. After learning about purely JavaScript-driven web pages, I have been enhancing individually rendered views (often provided by a PHP Framework) with AngularJS to add more functionality. However, m ...

Angular JS page in its purest form

I have successfully developed a single-page application using AngularJs. However, when I visit the main page of my application hosted on the Heroku server, for a brief moment, all the images and text appear in a raw state at the top left corner of the bro ...

Guide on executing a jar file using JavaScript and obtaining a JSON output

Is there a way to execute and capture the output of a jar file that returns a json using javascript? ...

Utilize Javascript to pull information from a REST API and generate a dynamic table with the retrieved

Generating a table from JSON data obtained from a REST API without utilizing Angular poses a challenge in a specific application. My query is: Is it necessary to use var table = document.createElement("TABLE"); within the script to construct the entire ta ...

The NoUiSlider had already been initialized

Currently, I am facing an issue when trying to incorporate noUiSlider with Angular JS. I have a directive that contains 4 sliders and I intend to display this directive on 2 different pages. However, each time I switch between the pages, an error occurs st ...

Material-UI rating component outputs a string instead of a numerical value

I'm encountering an issue with the Material UI rating component. Despite providing it with a number as the initial value (this.props.data.feelings_rating), it returns a string whenever I change it within my app. Below is the relevant code: Rating co ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

What sets Koa apart when it comes to understanding the distinctions among await next(), return await next(), return next(), and next() in middleware?

The provided information explains the function of using 'await next()' in middleware to pause the middleware and initiate the next middleware downstream until all middlewares have completed execution. Once this happens, the process will start in ...

Tips for properly modifying an attribute within an array of objects in JavaScript using ReactJS

My array of objects looks like this: this.state = { itemSquare: [{ item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: ...

How can a Chrome extension automatically send a POST request to Flask while the browser is reloading the page?

I am looking to combine the code snippets below in order to automatically send a post request (containing a URL) from a Chrome extension to Flask whenever a page is loading in Chrome, without needing to click on the extension's icon. Is this feasible? ...

Unable to retrieve JSON data from the remote URL

I have been attempting to retrieve information from but unfortunately, I am not receiving any data in return. Despite this, I can see the data in my response tab using Google Chrome. My attempts include running it on both a webserver and locally for test ...

Tips for creating a hover effect on an icon within a CSS grid

I've just started learning to code and wanted to create a component for previewing/displaying a project I'm working on. I've been attempting to add a hover effect to my links such as the GitHubIcon and LaunchIcon, but so far, it's not w ...