I created a countdown function, but why isn't it producing any results?

Hey there! Below is my HTML code where I'm trying to implement a countdown function using AngularJS.

var app = angular.module('myCountDown', []);

app.controller("Countdown",function($scope){

$scope.start = function(){
var temp = $scope.inputValue;

setInterval(function(){
if(temp<1){
return ;
}
temp -= 1;
$scope.count = temp;
console.log($scope.count);
},1000);
}
})
    <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8>
<title>Document</title>
</head>
<body ng-app="myCountDown">
<div ng-controller="Countdown">
<input type="text" ng-model="inputValue">
<button ng-click="start()">Start</button>
<input type="text" ng-model="count">
</div>
<script src="angular.min.js"></script>
<script src="app.js"></script>
<

I have the result displaying in the console, but it's not showing on the webpage for some reason.

Thank you!

Answer №1

Opt for $scope.$apply() to instantly view your updates OR utilize $interval as the preferred method in Angular over setTimeout.

DEMO

var app = angular.module('myCountDown', []);
app.controller("Countdown", function($scope, $interval) {
  $scope.start = function() {
    var temp = $scope.inputValue;
    $interval(function() {
      if (temp < 1) {
        return;
      }
      temp -= 1;
      $scope.count = temp;
      console.log($scope.count);
    }, 1000);
  }
})
<!doctype html>
<html lang="en>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<meta charset="UTF-8>
<title>Document</title>
</head>
<body ng-app="myCountDown">
<div ng-controller="Countdown">
  <h1> {{count}}</h1>
<input type="text" ng-model="inputValue">
<button ng-click="start()">Begin</button>
    {{count}}
<input type="text" ng-model="count">
</div>

</body>
</html>

Answer №2

setInterval will be executed outside of angular's scope. To handle this within Angular, use $interval instead. It is important to clear the previous interval before creating a new one.

See the example below for reference.

var app = angular.module('myCountDown', []);

app.controller("Countdown", function($scope, $interval) {

  $scope.start = function() {
    var temp = $scope.inputValue;
    if ($scope.sampleInterval) {
      $interval.cancel($scope.sampleInterval);
    }
    $scope.sampleInterval = $interval(function() {
      if (temp < 1) {
        return;
      }
      temp -= 1;
      $scope.count = temp;
      console.log($scope.count);
    }, 1000);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myCountDown">
  <div ng-controller="Countdown">
    <input type="text" ng-model="inputValue">
    <button ng-click="start()">Start</button>
    <input type="text" ng-model="count">
  </div>
  <script src="angular.min.js"></script>
  <script src="app.js"></script>
</div>

Answer №3

To address this issue, I have a solution in mind that involves making modifications to the JavaScript file.

var app = angular.module('myCountDown', []);

app.controller("Countdown",function($scope){

$scope.start = function(){
var temp = $scope.inputValue;

setInterval(function(){
if(temp<1){
return ;
}
temp -= 1;
$scope.count = temp;
$scope.$apply();
console.log($scope.count);
},1000);
}
})

In order to activate the Angular application manually, we must remember to use $scope.$apply();

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

Despite using callbacks when passing props in React JS components, the rerendering still occurs

In my React project, I implemented callbacks to prevent excessive rerendering due to the large amount of data being displayed and numerous buttons that trigger these rerenderings when clicked by the user. The useCallback hooks are effective in preventing ...

Is there a way in JQuery to choose a checkbox within a neighboring div?

How do I use JQuery selectors to target and remove the disabled property from a checkbox within a specific sibling div (in this case, the div with the class of col-3)? Adding a class directly to the checkbox is not an option due to multiple occurrences of ...

How can I display base64 image data in a new window without triggering a block?

Currently experiencing challenges with Javascript. Utilizing html2canvas to convert a div to a canvas and then using .toDataURL to convert the canvas to a base64 data stream. Attempting to open base64 image data in a new window, but facing blocks from va ...

How to properly Open a "div" Element by its ID in ReactJS

Today, I want to share an issue that I've been facing. To simplify things, I have mapped a BDD, The result of this mapping is displayed in multiple cards, There's a button that when clicked opens up more details on the map, But here's wh ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...

metamorphosis array

I have a unique situation where I'm working with an SVG map containing a g element container. Within the g element, there are items with specific x and y positions. My challenge is to create a mouse wheel zoom function that pans the g element in a wa ...

Utilizing Axios recursion to paginate through an API using a cursor-based approach

Is there a way to paginate an API with a cursor using axios? I am looking to repeatedly call this function until response.data.length < 1 and return the complete array containing all items in the collection once the process is complete. Additionally, I ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

Gather information from a line of Javascript using Python's scraping capabilities

Is there a way to extract JSON data from a Javascript line using Python? AH4RSearch.listingsJSON = $.parseJSON('{"properties":[{"Price":3695,"PriceFormatted":"3,695","Street":"9251 E Bajada Road&q ...

Trouble with anchor tag event activation

I'm having an issue where my anchor onclick event is not triggering. Below is the jquery code I am using: This function runs on page load: function pageLoad() { I am binding the context menu event to an anchor element: $('#ctl00_ContentPlaceH ...

What is the best way to extract a JSON string from the login PHP response?

I am working on creating a basic website along with an Android application that both retrieve data from the same database. While I have no issues in dealing with Android, I am facing difficulty in handling JSON strings in HTML. How can I fetch the JSON res ...

Obtain the vector for the right hand using three.js

I am looking to obtain the forward vector of an Object3D in Three.JS var forward = new THREE.Vector3(); object.getWorldDirection(forward); Is there a way to retrieve the right-hand side vector of the object within Three.JS framework? ...

Error: The term "User" has not been previously defined

I encountered an issue while attempting to authenticate via vkontakte (vk.com) using passport-vkontakte. Error: A ReferenceError: User is not defined Below is the content of my auth.js file. var express = require('express'); var passport ...

What potential problem is arising from Jest's use of "transformIgnorePatterns" and how does it impact importing scoped CSS in a React application?

Currently facing a challenge with Jest testing in my React application following the addition of transformIgnorePatterns to the Jest settings. The default settings I included in the "jest" section of the root package.json file are as follows: "transfo ...

Display the DIV specifically for visitors arriving from Facebook

I want to display a specific DIV on the product page only if the user has visited from Facebook. Currently, I am using the following code to check if they arrived from Facebook: var ref = document.referrer; if (ref.match(/^https?:\/\/([^\ ...

Solution for handling pointer events in Safari iOS when they are not supported

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/pointerdown_event Hello! I have successfully implemented code for a long click, however, the pointer event api is not fully supported in Safari as it is still under development. Is there a simp ...

What is the best way to include a form within every row of an HTML datatables structure?

I have a regular table that is populated with data fetched via Ajax, and it appears like this: Ajax <script> $(document).ready(function() { $('#mytable').DataTable( { "ajax": "myurl", "dataType": 'json', ...

Why doesn't the Iframe onLoad event trigger when uploading a file?

I have a straightforward iframe <iframe class="ifr" src="about:blank"></iframe> It contains an onload handler. $(".ifr").on('load',function (){ alert("iframe loaded") }); There are also two buttons: Pressing the first button ...

Exploring best practices for transmitting JavaScript objects and arrays via forms to servers (JSON/??)

I would like to understand what would be the most effective approach to achieve this: Based on a user selection, generate a list of "selected items" in the following format: {items {categoryString {tag_id1 {[fr]=>itemFR, [en]=>itemEN} {c ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...