K
K
Knyashshsh2018-02-16 15:21:35
JavaScript
Knyashshsh, 2018-02-16 15:21:35

How to create a global variable?

There is an ajax request

//ajax под грузка сообщений на странице поста
        function getMessages() {
            $.ajax({
                url: "ajax/postComments.php",
                method: "POST",
                data: ({postID: <?php echo $id ?>}),
                dataType: "html",
                success: function (data) {
                    $('.author-messages-list').empty();
                    $('.author-messages-list').append(data);
                }
            });
        }
        var timer = getMessages();
        var timerPostAuthor = setInterval(function() {
            getMessages();
        }, 2000);


And it must be stopped, for this
//Останавливаем таймер на странице поста
    $(document).on('keyup change', '#posttext', function () {
        clearInterval( timerPostAuthor );
    });

But timerPostAuthor is not visible (timerPostAuthor is not defined writes to console and phpstorm)
How to make timerPostAuthor a global variable?
Full js
$(function () {

        //ajax под грузка сообщений на странице поста
        function getMessages() {
            $.ajax({
                url: "ajax/postComments.php",
                method: "POST",
                data: ({postID: <?php echo $id ?>}),
                dataType: "html",
                success: function (data) {
                    $('.author-messages-list').empty();
                    $('.author-messages-list').append(data);
                }
            });
        }
        var timer = getMessages();
        var timerPostAuthor = setInterval(function() {
            getMessages();
        }, 2000);

});

//Останавливаем таймер на странице поста
$(document).on('keyup change', '#posttext', function () {
   clearInterval( timerPostAuthor );
});

We are looking in the document because the form comes with an ajax request and this code (which is below) will not work stupidly
$('#posttext').on('change', function () {
    clearInterval(timerPostAuthor);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nick Sdk, 2018-02-16
@fyapy

global variables in js like this: Global object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question