Tips for resetting and configuring timer feature?

A feature in my quiz app requires setting up a timer in the controller that counts for 30 seconds and stops the quiz if there is no activity within that time frame. The timer should reset and start counting again if there is any activity. I have implemented web socket listeners for this functionality. How can I correctly set up the timer?

This snippet shows my controller code:

angular.module('quiz.controllers')
.controller('MultiPlayerQuestionController', function(
  $scope,
  $rootScope,
  $state,
  $stateParams,
  $timeout,
  UserService,
  QuizService,
  InviteService,
  MessageService,
  SocketService
) {
  // Controller logic here
});

I attempted to call the responseTimer function I created in the controller by initializing it at the beginning like this:

responseTimer(30000);

Later on, I defined the function as follows:

var responseTimer = function (time) {
    responseTimer = $timeout(stopQuiz, time);
    console.log('Started timer');
};

var resetResponseTimer = function () {
    $timeout.cancel(responseTimer);
    responseTimer(30000);
    console.log("Timer reset");
};

However, I encountered an error message:

TypeError: responseTimer is not a function

Answer №1

The issue arises from a conflict in scope within your code

// Declaring responseTimer as a global function
var responseTimer = function (time) {

   // Without the var keyword, the scope of responseTimer becomes global instead of local, overriding the previous declaration
   responseTimer = $timeout(stopQuiz, time);

This is why you are encountering the error

 responseTimer is not a function

To resolve this problem, include the var keyword before the second declaration and choose descriptive variable names. It's advisable to use an action verb when naming functions/methods, such as using triggerResponseTimer for the function name and responseTimer for the variable name. Your updated portion would look like:

var triggerResponseTimer = function (time) {

    var responseTimer = $timeout(stopQuiz, time);

Answer №2

For optimal results, consider using $interval over other options: Check out this great example:

Another useful resource: $interval

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

The duration of recorded audio in JavaScript is unclear

I managed to successfully create a structure for recording and downloading audio files. However, I'm facing an issue where the final downloaded file has an unknown duration. Is there any way to solve this problem?? Here is my Typescript code snippet: ...

The value of 'this.selectedNodes' does not support iteration and is causing a

I am currently utilizing v-network-graphs to generate graphs in the front end with Vue. I have set up my data like this: data(){ return{ test: test_data, nodes:{}, edges:{}, nextNodeIndex: Number, selectedNodes: ref<st ...

What is the impact of Javascript variable scope in the context of "for...in..." loops?

Imagine you have a code snippet like this: dict = {"key":"elem"} for (var elem in dict){ someFunction(function(){ anotherFunction(dict[elem]); }) } Question: Is elem still considered as the temporary variable created in the for...in... s ...

Dynamic links with Node Acl

Utilizing the npm module Acl to establish an ACL system has been my current focus. You can check out the homepage of this module at: https://github.com/OptimalBits/node_acl. While the documentation provides straightforward examples for granting role acces ...

Iterating over an object using ng-repeat in Angular, where the value is an array

In my data object, I have key-value pairs where the value is an array. Each array contains objects with various properties. $scope.testObj = { "London":[ {"id":1,"city":"London","country":"GB","name":"Test1"}, {"id":4,"city":"London" ...

How can you pass two distinct variables in a JavaScript function?

This is the JavaScript code for my first page: <script> function MessageDetailsById(id) { $("#active"+id).css({"color":"red"}); var http = new XMLHttpRequest(); var url = "Ajax.php"; ...

Converting Custom Data Arrays to JSON using JavaScript

My goal was to create a utility function that can convert custom data (the type of data Sencha Touch stores use) into JSON format. I've made progress, but the function fails when dealing with complex data from the Twitter API, although it works fine w ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

Decode the string containing indices inside square brackets and transform it into a JSON array

I have a collection of strings that contain numbers in brackets like "[4]Motherboard, [25]RAM". Is there a way to convert this string into a JSON array while preserving both the IDs and values? The desired output should look like: {"data":[ {"id":"4","i ...

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...

What is the procedure for selecting an element based on its child containing specifically filtered text?

Imagine a webpage with the following elements: <div data-search="type1"> any HTML <!-- .click is a child of any level --> <span class="click" data-source="page1.html">blue</span> <!-- let's call it "click1 ...

Expanding the padding of the selected item to create more breathing room

Upon examining the following: https://jsfiddle.net/h8kmove5/27/ Let's say you select 9 at the bottom. The display shows 8 9 10. My intention is to create some additional space on either side of 9, or any other active item for that matter. This way, ...

Sequelize associations are not functioning optimally as expected

Trying to display a nested relationship: Cat.hasMany(legs) Leg.belongsTo(cat) Leg.hasOne(paw) paw.hasMany(leg) This is the Cat Model: module.exports = (sequelize, DataTypes) => { const Cat = sequelize.define('Cat', { us ...

Adjust the input values based on the child elements within the main container

Here is a series of DIVs with unique IDs: <div id="2988"> <div class="site">YaHoot.com</div> <div class="logo">/images/yahootLogo.jpg</div> //[and so on] <input type="button" value="YaHoot" onclick="javascript: ...

Correctly align the div on the screen as the viewport is scrolled

I am currently working on a parallax website where the sliders are designed to slide from the left and align within the viewport as the user scrolls. However, I have encountered an issue where multiple scroll actions are required for the slide to align pro ...

Convert the data into a format that is compatible with JavaScript

Having trouble extracting a value from json and placing it into my controller. I want to assign the membership value of 8 to $scope.value = data.membership; Service call in JS: .service('getMembership', function ($http, SERVER_URL) { r ...

Alerts for drop down menu validation with multiple buttons

My goal is to design a multi-step form that collects user information. This form consists of 5 stages: Step 1: User details (Name, email, phone, age, gender) Step 2: Yes or No question Step 3: Yes or No question Step 4: Yes or No question Step 5: Yes o ...

Javascript 'break' statement is always executed

It seems like I'm overlooking a very basic concept here. Why isn't my code reaching the else statement? The issue might be related to the break statement. It's likely something simple that I am missing. Code Snippet: <button onclick="yo ...

AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application. My app is a brand new Angular cli project following the mentioned guide. My objective is to utilize the standalone auth components a ...

What is the best way to check the difference between the current date and time with another date and

Seeking assistance in comparing 2 dates using JavaScript has been a bit challenging for me. I haven't found the exact solution on this platform yet. As a beginner in JavaScript, I initially assumed that obtaining the current date and time would be a s ...