Issue with conditions in window.setTimeout function

I've been grappling with a website that features a loading page lasting 5 seconds, during which users can choose to activate autoplay or not. However, even after implementing a condition in my code, the autoplay feature continues to run unexpectedly. Here's the code snippet - I hope someone can provide some assistance.

body .loading {
  text-align: center;
}

body #content {
  display: none;
}
<!doctype html>
<html lang=en>

<head>
  <meta charset="UTF-8">
  <title>Home</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>

<body>

  <div class="loading">
    <input type="button" value="Click Here to mute" class="autoplay" id="autoplayno" />
  </div>

  <div id="content">
    <iframe class="embed-responsive-item" id="iframesc" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/users/334742776&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true&start_track=1"
      allow="autoplay"></iframe>
  </div>

</body>

<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<!--Loading Page-->
<script>
  $(".loading").fadeOut(5000, function() {
    $("#content").fadeIn(2000);
  });
</script>

<!--The script which is not working-->
<script>
  var hasBeenClicked = false;
  $("#autoplayno").click(function() {
    hasBeenClicked = true;
  });

  if (hasBeenClicked) {
    $("#iframesc").attr("src", "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/users/334742776&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true&start_track=1");
    $("#autoplayno").attr("value", "Sound mutted");
  } else {
    window.setTimeout(function() {
      $("#iframesc").attr("src", "https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/users/334742776&color=%23ff5500&auto_play=true&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true&start_track=1")
    }, 4000)
  }
</script>


</html>

Answer №1

hasBeenClicked initially has a value of false.

The code inside the if statement will execute when hasBeenClicked is false. Otherwise, the code within the else block will run.

In the future, if someone clicks on the autoplay button and changes the value of hasBeenClicked to true, it may not affect the logic as you have already selected the URL without revisiting this variable.

You may consider encapsulating the entire code block within the if statement in a function that is passed to setTimeout instead of placing only the contents of the else block within setTimeout.

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

`How can I relocate an IFRAME within a DIV?`

Users have the ability to freely edit HTML content, which is fine. However, I need to relocate all IFRAME elements into a DIV. I attempted the following code: $('#rolunk_content iframe').html ('<div>1' + $('#rolunk_content i ...

Is it more advantageous in Vue to pre-process and save data directly to the data property, or to utilize computed properties?

I am interested in hearing diverse perspectives on this topic. When working with Vue (and possibly other frameworks), is it more beneficial to prepare non-reactive data through a method and store it in the data for use in the template, or is it preferable ...

What is the process for utilizing npm/yarn installations within a .Net Framework WebAPI project?

In my project, I utilize SCSS and would like to incorporate Bootstrap.scss in order to create a single class that inherits multiple Bootstrap classes. For instance: .myButtonClass { @col-xs-12; @col-sm-6 } This way, I can replace class="col-xs-12 col-sm- ...

When utilizing array.push() with ng-repeat, it appears that separate scopes are not generated for each item

I'm currently working on an Angular View that includes the following code snippet: <div ng-repeat="item in items track by $index"> <input ng-model="item.name"/> </div> Within the controller, I utilize a service to retrieve a Js ...

Creating a simple jQuery dropdown menu from the ground up

I'm currently working on creating a simple drop-down menu using jQuery. The idea is to have a button inside the top navigation that, when hovered over by a user, triggers a div to slide down below it. Here's the code snippet I've put togethe ...

Having trouble with an onClick function not working on a .php webpage?

I recently developed a simple JavaScript script that dynamically loads an image based on user input in a text field (e.g., entering 'brick1' loads brick1.jpg). Although this works fine on a regular HTML page, I faced issues triggering the onClick ...

Just updated to Angular 10, encountered issue: Unable to modify the read-only property 'listName' of an object

After updating my Angular project from version 8 to version 10, I encountered an error while trying to edit an input field in a Material Dialog. The error message displayed is as follows: ERROR TypeError: Cannot assign to read only property 'listName& ...

JQuery: Implementing automatic selection in a selectbox

Seeking assistance on how to automatically preselect a value in a select box. I am trying to have the select box automatically choose admin aid VI, but my script is not functioning correctly. Can anyone provide guidance on this issue? Here is the HTML co ...

Converting SVG with an external PNG file embedded into a standalone PNG format using Node

Does anyone know of a node package that can convert an svg file to a png, including external images embedded within the svg code like this? <?xml version="1.0" encoding="utf-8"?> <svg viewBox="0 0 120 120" height="120" width="120" xmlns="h ...

Tips for extracting an SVG path from HTML structure

This example I'm referencing is by Chris Coyer <svg version="1.1" xmlns="http://www.w3.org/2000/svg" mlns:xlink="http://www.w3.org/1999/xlink" style="display: none;"> <defs> <g id="icon-image"> <path class="path1" d="M0 4v26h32v ...

Send myArray via ajax to php

Hey there, I'm currently working on passing an array called myArray to PHP. <script type = "text/javascript" > $(document).ready(function () { var tagApi = $(".tm-input").tagsManager(); var myArray = []; jQuery(".t ...

Press on the button that is currently in your field of view

I have a web page with multiple buttons inside div elements. I am looking to automate the process of clicking the "Buy" button that is currently visible on the screen when the user presses the B key. $(document).keydown(function(e) { if (e.keyCode == ...

Improving animation performance on mobile devices using AngularJS

I've reached the final stages of developing a mobile application using AngularJS wrapped in a cordova webview. However, I'm encountering some issues with the panel transition animations. After experiencing strange behavior with ngAnimate, I deci ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then( ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

Is the order of execution of extraReducers before or after the reducers?

I was curious about the createSlice function in redux-toolkit and how it handles the order of execution for extraReducers compared to reducers. Can we determine if the extraReducers are executed before or after the reducers, or is the order indeterminate? ...

How can I submit a form or retrieve HTML content using JavaScript without using an iframe?

Background: My current job involves transcribing paper reports using a webapp that is quite old and cannot be updated or connected to a database directly. The system only checks for duplicate unique IDs once the entire form is submitted. This often leads ...

What is the process for customizing the image size of a WordPress RSS feed in pixels?

Is there a way to customize image sizes beyond the 'thumbnail', 'medium', and 'large' options? I tried setting width and height in the <img> tag within an RSS file, but it didn't work. Could it be a nested quotation ...

Instructions on enabling checkbox functionality within a dropdown menu using BootstrapVue.js

Can someone help me troubleshoot this dropdown issue in bootstrapvuejs? I'm having trouble checking the boxes before the dropdown closes. Any suggestions on how to fix this? <template> <div class="inventory-filter-button"> ...

tips for modifying html element attributes using angular

I am working with an element that is automatically generated through an API call as <a target="_blank" href="http://www.work.com/reward"><b class="orange tdu">My Work History</b></a> and now I want to modify it like <a ng-cl ...