Flashing background colors on a website

Can anyone explain why this code won't alternate the background color of my website between two different colors?

<script type="text/javascript">
function blinkit() {
    intrvl = 0;
    for (nTimes = 0; nTimes < 3; nTimes++) {
        intrvl += 1000;
        setTimeout("document.bgColor='#0000FF';", intrvl);
        intrvl += 1000;
        setTimeout("document.bgColor='#FFFFFF';", intrvl);
    }
}
</script>

Answer №1

Give this a try:

function pulseColor() {
    interval = 0;
    window.setInterval(function(){
        interval += 1000;
        setTimeout("document.bgColor='#FF0000';", interval);
        interval += 1000;
        setTimeout("document.bgColor='#FFFFFF';", interval);
    }, interval);
}

Answer №2

Avoid passing strings to the setTimeout function, as it is just as risky as using eval.

Instead, consider implementing a function like this:

function blinkEffect(repetitions, callback) {
    var toggle = repetitions*2, timer = setInterval(function() {
            document.body.style.backgroundColor = toggle%2 ? "#0000FF" : "#FFFFFF";
            toggle--;
            if( !toggle) {
                clearInterval(timer);
                callback && callback();
            }
        },1000);
    return timer;
}
var flashing = blinkEffect(3);
// The background will flash three times.
// You can also stop it with `clearInterval(flashing);`

Using the provided code snippet, you have the option to specify an action to be taken upon completion:

var flashing = blinkEffect(3,function() {alert("Hello!");});

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

Specify the title attribute by using a language-based string

Can the title attribute content on an image be defined as a language string that can be overridden in a multilingual website? I am considering following this format: <img title="tooltip_mod".....> Creating a tooltip_mod INI file that defi ...

Loading 3D models in Three.js from the cache

Every time my page reloads, the loader loads objects from the URL instead of cache. Is there a way to check if the resource is in cache and load it directly? Appreciate your help! ...

Dropdown sidebar with collapsible sections

I am looking to create a unique navigation system for my website. I have a standard HTML list with menu items that will serve as anchor links on a long-scrolling page. My idea is to design it as a minimal vertical side navigation bar, where each item initi ...

Safari on the iPad does not support opening debugging through the HTML tag

Currently, I am attempting to debug a website using Safari on a MacBook connected to an iPad. However, I am facing an issue where the tags cannot be opened for inspecting the content. When I try to open the wrapper, it does not expand to reveal the content ...

Validation of PO Box Addresses Using Regular Expressions

I'm having trouble getting the alert to work with my code. $(document).ready( function (){ $("[id*='txtAddress1S']").blur(function() { var pattern = new RegExp('\b[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*& ...

Guide to importing a JSON file into Vue.js and HTML

I'm a beginner in Vue and not very familiar with HTML I'm attempting to import data from a JSON file into my interface to display it for the user. Below is the structure of the JSON: [ { "Title": "SOFT-STARTER", "Cod&q ...

Displaying the age figure in JSX code with a red and bold formatting

I have a webpage with a button labeled "Increase Age". Every time this button is clicked, the person's age increases. How can I ensure that once the age surpasses 10, it is displayed in bold text on a red background? This should be implemented below t ...

Struggling to retrieve Ajax data and assign it to a PHP variable?

My Code Snippet is: <script> $(document).ready(function(){ $(".states").on('click','option',function(){ var selectedValue = $("select[id='stateId'] option:selected").val(); $.post('<?p ...

Troubleshooting issue: Angular not resolving controller dependency in nested route when used with requirejs

When the routes are multiple levels, such as http://www.example.com/profile/view, the RequireJS is failing to resolve dependencies properly. However, if the route is just http://www.example.com/view, the controller dependency is resolved correctly. Below ...

Styling with CSS in a React component

I am trying to display a row of buttons instead of columns on my webpage. I have used display:flex but it is still showing as a column. What I want is for each button to display the first character of its name underneath it, with all buttons lined up next ...

Divide and Insert a Gap in Phone Number

I need help formatting a telephone number so that there is a space between every third and seventh character. var phoneNum = "02076861111" var formattedNum = [phoneNum.slice(0, 3), phoneNum.slice(3,6), " ", phoneNum.slice(6)].join(''); console ...

Troubleshooting: JQuery anchor scrolling malfunctioning in Internet Explorer

I'm currently learning how to use javascript and jquery and have incorporated some pre-made components on my website. Feel free to check it out at However, I've encountered an issue where when I click on a link to scroll down to a specific ancho ...

A problem arises when trying to showcase the content in a responsive manner on the hamburger menu, particularly when viewing on mobile

As a newcomer to web development, I decided to challenge myself by building an E-Commerce website to enhance my skills. To ensure mobile responsiveness, I opted for a hamburger menu to hide the navbar content. However, despite resizing working flawlessly, ...

The Navbar Button is having trouble with vertical alignment

I've been experimenting with Bootstrap to customize a navbar to my liking. I'm having trouble getting everything vertically centered properly in this menu, as you can see in my code. I've made some okay adjustments by tweaking the margin, bu ...

Issue with onblur and focus while returning back from external window

Instructions to reproduce the issue: Important: Set up two input fields with names and add a console.log("Test Focus In" + element.getAttribute("name")) and console.log("Test Blur" + element.getAttribute("name")) statement in the focusin and blur event f ...

Using DataTables with PHP and AJAX allows for the ability to modify the data before it is displayed

Typically, I prefer not to use dataTables with AJAX calls, instead opting to run SQL queries and insert the results directly into a table. However, for the sake of expanding my skills, I want to explore using dataTable with AJAX. I am a bit unsure about ho ...

How to play audio with a source path that includes the special character "%" in JavaScript

Having an issue with playing an audio file that has '%' in its name. I've tried using the tag <audio src="test%320.mp3" controls></audio>, but it seems like the file is not being found when I try to play it. Can anyone ...

Interacting with a RESTful Service on a separate server

I need assistance with a JavaScript method snippet that I have included below: var tempUrl = "http://A.com:8081/TestService/serviceMethod"; jQuery.ajax({ url:tempUrl, type: 'POST', data:"getDatareq="+encodedata, contentType: 'app ...

What does "SPAN CLASS="SKYPE_C2C_FREE_TEXT_SPAN" refer to?

While browsing a website, I noticed the use of this HTML class surrounding customer address information entered in a form. I am curious about the purpose of these tags - perhaps they trigger a specific behavior on Skype? Unfortunately, I couldn't find ...

JavaScript and the importance of using commas in arrays

I am developing a system that displays text in a textarea when a checkbox is checked and removes the text when the checkbox is unchecked. The functionality is mostly working as intended, but I am facing an issue where commas remain in the textarea after un ...