What is the best way to pause a JavaScript JSON stream for 60 seconds?

I have been tasked with creating a JavaScript program that retrieves an API JSON record from a specific address every minute through a WebSocket. The stream should continue after 60 seconds, and I need to return both the current stream and the previous one that was retrieved. Below is the code I have written:

var obj= 
{
    seconds : 60,
    priv : 0,
    prevTick : '' ,
    data : ''
}

function countTime()
{
    obj.seconds --;
    obj.priv ++;
    var message ;
    if(obj.priv > 1)
    {
        obj.priv = 0;
        obj.message = null;
    }
    if(prop.seconds < 0)
    {
        message = sock.open();

        obj.message = obj.message + ", New Tick : " + message.message ; 
        setTimeout(countTime, 1000);
        obj.seconds = 60;
    }

}

var sock= new WebSocket('link');


sock.onopen = function(evt) {
    ws.send(JSON.stringify({ticks:'string'}));
};

sock.onmessage = function(msg) {
   var data = JSON.parse(msg.data);
   return 'record update: %o'+ data ;

};

Can someone please help me identify what is incorrect in my code above? It doesn't seem to be delaying as expected, and the stream continues continuously.

Answer №1

Have you considered creating a class to manage the buffering functionality?

class SocketBuffer {
    constructor(socket, delay, ontick) {
        this.messages = [];
        let tickInterval;

        socket.onmessage = function(msg) {
            this.messages.push( JSON.parse(msg.data) );
        };

        function tick() {
            if (typeof ontick !== "function") return;
            ontick( this.messages.splice(0) );
        }

        this.pause = function () {
            tickInterval = clearInterval(tickInterval);
        };
        this.run = function () {
            if (tickInterval) return;
            tickInterval = setInterval(tick, delay * 1000);
            tick();
        };
        this.run();
    }
}

It's important to note that .splice(0) will extract all elements from the array and clear it in one step.

Example:

const link = new WebSocket('link');
link.onopen = function (evt) {
    this.send( JSON.stringify({ticks:'string'}) );
};

const linkBuf = new SocketBuffer(link, 60, function (newMessages) {
    console.log(newMessages);
});

// If necessary, you can:
linkBuf.pause();
linkBuf.run();

Answer №2

Give this a shot:

function calculateDuration() {
    var timeInterval = 1000; // Time interval between each calculation
    // setInterval continues to run indefinitely unless stopped with clearInterval
    var timer = setInterval(function () {
        // Insert your code here

        // End the loop if needed
        clearInterval(timer);
    }, timeInterval);
}

Answer №3

By utilizing setTimeout(), you can automate the process without manually tracking seconds. For tasks that need to be repeated periodically, it is recommended to use setInterval() as advised by @RyanB. On the other hand, setTimeout() is more suitable for one-time tasks. It appears that you are referencing prop.seconds without defining the variable prop. Remember to include a call to countTime() somewhere in your code to ensure its execution.

An improved version may look like this:

var obj= 
{
    seconds : 60,
    priv : 0,
    prevTick : '' ,
    data : ''
}

function countTime()
{
    obj.seconds --;
    obj.priv ++; //It seems redundant to set it back to zero 3 lines later
    var msg ;
    if(obj.priv > 1)
    {
        obj.priv = 0;
        obj.msg = null;
    }
    msg = sock.open();
    obj.msg = obj.msg + ", New Tick : " + msg.msg; 
    obj.seconds = 60;
    //Consider calling sock.close() here
}

var sock= new WebSocket('link');

sock.onopen = function(evt) {
    ws.send(JSON.stringify({ticks:'string'}));
};

sock.onmessage = function(msg) {
   var data = JSON.parse(msg.data);
   return 'record update: %o'+ data ;

};
var interval = setInterval(countTime, 1000);

EDIT: Once completed, use

clearInterval(interval);

to terminate the program's execution.

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

"Encountering Validation Error while Transmitting JSON Data through AJAX with NodeJS and M

After completing the form input, I am trying to send it as JSON via AJAX to the server. However, upon sending the data, a message from the server pops up saying "ValidationError: Post validation failed: text: Path 'text' is required." When I chec ...

The 'AutocompleteDirectionsHandler' cannot be utilized until the Google Api has been initialized

Attempting to utilize the Google Maps and Autocomplete API is proving challenging. The error encountered reads: Uncaught (in promise) ReferenceError: Cannot access 'AutocompleteDirectionsHandler' before initialization at window.initMap (traf ...

Tips for troubleshooting the StaleElementReferenceError in selenium automation

Encountering the persistent issue of receiving the error message StaleElementReferenceError: stale element reference: element is not attached to the page document every time I attempt to extract the text from a page body using Selenium. Numerous attempts h ...

Maximizing the efficiency of this JavaScript code

Is there a way to optimize this code for better efficiency? I'm trying to enhance my coding skills and would appreciate some feedback on this particular section: $(function(){ $('#buscar').focus(function(){ if(($(this).val() === ...

Initiate jison states using JSON structure

After an extensive search through documentation and forums, I am still struggling to find the correct syntax for Jison start condition using JSON format in node.js. > ** The documentation at http://zaach.github.io/jison/docs/ states: > // Using the ...

Issue with div data-anchors not functioning unless the entire page is reloaded

My WordPress website has various chapters represented by different divs. Each div corresponds to a page, and at the bottom, there is a button that allows users to navigate to the next div. Although the script is functioning properly, the site does not smoo ...

The mapDispatchToProps function is failing to work, throwing an error: Uncaught TypeError: _this.props.addCountdown is not a function

Currently, I am facing an issue while working on my first app. The problem arises with a form component that should send an object via an onSubmit handler. onSubmit = (e) => { e.preventDefault(); this.props.onSubmit({ title: ...

Leveraging Vue.js plugin within a single file component

I am looking to utilize the vue-chartkick plugin in my Vue application, but I want to register it within my single-file components instead of globally. Is there a way to achieve this same functionality without using Vue.use(VueChartkick, { Chartkick })? ...

What is the best way to compare the lengths of all nested child elements with each other?

I have an object with nested children, like this: $scope.artists.materials.items[] //contains list of items Now I need to compare the total length of each artist's list of items. If there is a mismatch in the number of items between artists, I want ...

Discover the power of uploading images using HTML5 with PHP

Is there a way to retrieve values of uploaded images after clicking on the submit button using $_POST in PHP (with image upload through HTML5)? For an example of HTML5 image upload, you can check out this link You can access the demo at the following lin ...

Puppeteer encounters difficulty when attempting to click on a particular div element within Gmail

I am attempting to click on the three dots in Gmail by following this link: 1 After that, I want to click on the 'mark all as read' option: 2 Clicking on the three dots works without any issues. However, I am encountering difficulty when tryin ...

One way to transfer data from a Vue table component to another Vue table component is by including an edit button on each row in the table. This allows

When working with two table components, one fetching records using axios and the other needing to get records after clicking on the edit button in the parent component, I encountered issues. Despite attempting Vue's parent-to-child component communica ...

Comparing elements in one array to elements in another array

In AngularJS, the $scope.categories array is populated from a multi-select element. $scope.categories = ["Adventure", "Strategy"] To compare this array with the categories in the items array below: $scope.items = [ { title: "Star Wars", ...

What is the best way to ensure that this JavaScript code functions properly when dealing with business operating hours

Using this javascript code allows me to check if a business is open based on its operating hours. It's effective for times like 17:00-23:00, but how can I modify it to work for hours past midnight, such as 0:30 or 1:00 in the morning? var d = new D ...

Utilizing jQuery event delegation with the use of .on and the unique reference of (

Questioning the reference in a delegated .on event: Example: $('#foo').on('click', $('.bar'), function() { console.log(this); }); In this scenario, `this` will point to #foo. How can I access the specific bar element tha ...

JavaScript getter function is returning undefined even though it functions properly during the initial invocation

After successfully using a getter in pug the first time, it later returns undefined even though the code remains consistent. What could be causing this issue? The Question object class and its associated getter: class Question { constructor(op, min, ma ...

Nuxt.js transition issue: How to fix transitions not working

LOGIC: The pages/account.vue file consists of two child components, components/beforeLogin and components/afterLogin. The inclusion of child components is based on a conditional check within pages/account.vue using a string result ('x') stored in ...

Determining if a JavaScript variable points to another variable

Is there a way to identify if a variable is simply a reference to another object, and if so, determine the original variable name? For example, when trying to json encode an object that contains a property referencing back to the original object, it can l ...

What is the best way to insert values from an array into a row?

Is there a way to insert values from an array into separate cells in exceljs? I attempted the following approach: const columns = ['string', 'string2', 'string3']; for(let i=0; i < columns.length; i++) { workSheet.get ...

Error in Node REPL: Trying to access property '0' of undefined after adding a property to Object.prototype

After adding the name property to Object.prototype and attempting to reference Object.prototype, an error is encountered: TypeError: Cannot read property '0' of undefined" Although I am able to access Object.prototype.name, it seems like the na ...