Как запустить функцию setInterval после использования метода clearInterval?- JavaScript - PullRequest
0 голосов
/ 25 октября 2018

У меня есть сомнения .... Можно ли снова запустить функцию setInterval() после использования метода clearInterval()?

    var statistiche_recenti_storico = 0;
    var orologio_statistiche_recenti;
    orologio_statistiche_recenti = setInterval(function() {
      if (statistiche_recenti_storico == 0) {
        statistiche_recenti_storico = 1;
        alert('end');
        clearInterval(orologio_statistiche_recenti); 
      }
    }, 5000);

    $('#ok').on('click', function(){
        // ????
    });

Я хочу снова запустить orologio_statistiche_recenti после нажатия #ok.Возможно ли это?

Этот код находится внутри ready() события ( JQuery ).

Большое спасибо и извините за мой английский ...

РЕДАКТИРОВАТЬ Вот пример jsfiddle: https://jsfiddle.net/tr9hw30a/

Ответы [ 3 ]

0 голосов
/ 25 октября 2018

	//ogni secondo lancio questo codice con il setInterval
	var statistiche_recenti_storico = 0;
	var orologio_statistiche_recenti;

    var startTimeout = function() {
        if (orologio_statistiche_recenti) {
            clearTimeout(orologio_statistiche_recenti); //interrompo questo setInterval
        }
        orologio_statistiche_recenti = setTimeout(function() {
        console.log('timeout executed');
   	  if (statistiche_recenti_storico == 0) {
	    statistiche_recenti_storico = 1;
	    alert('end');
	  }
	}, 5000);
      }
      startTimeout();

$('#ok').on('click', startTimeout);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ok">OK</div>

На самом деле кажется, что вы хотите установить тайм-аут вместо интервала.Вы останавливаете его после первого исполнения.

0 голосов
/ 25 октября 2018

Создайте функцию и вызовите ее в своем коде, что является жизнеспособным подходом.

Я обернул ваш код в IIFE, это мешает «переменным» стать частью глобальной области видимости, вы говоритеу вас есть код внутри функции готовности jQuery, так что это вам не нужно.

Я определил функцию 'startInterval', она обрабатывает создание вашего интервала, она вызывается внизу скрипта,и в обработчике кликов.Обратите внимание: если вы не хотите использовать интервал после запуска сценария, удалите вызов startInterval в нижней части сценария, оставив только вызов в обработчике щелчков.

Я также сделалпроверка в функции startInterval для очистки любого существующего интервала, который выполняется, т. е. для остановки дубликатов.

// Wrapped in ann IIFE for scoping
(function () {

    var statistiche_recenti_storico = 0;
    var orologio_statistiche_recenti;

    // Define a function which handles the creation of your interval
    function startInterval () {

        // Delete any existing interval
        if (orologio_statistiche_recenti) {

            // You could add a return here instead...
            clearInterval(orologio_statistiche_recenti);
        }

        orologio_statistiche_recenti = setInterval(function() {
            if (statistiche_recenti_storico == 0) {
                statistiche_recenti_storico = 1;
                alert('end');
                clearInterval(orologio_statistiche_recenti); 
            }
        }, 5000);
    }


    $('#ok').on('click', startInterval);

    //Start your interval, by invoking the function
    startInterval();

})();

Полный пример ниже.Вышеописанное работало просто отлично, ваше оповещение срабатывало только один раз из-за вашего заявления IF, интервал фактически срабатывал.

<!doctype html>
<html>
    <body>

        <button id="ok">OK</button>
        <script
            src="https://code.jquery.com/jquery-2.2.4.min.js"
            integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
            crossorigin="anonymous">
        </script>

        <script>
            // Wrapped in ann IIFE for scoping
            (function () {

                var statistiche_recenti_storico = 0;
                var orologio_statistiche_recenti;

                // Define a function which handles the creation of your interval
                function startInterval () {

                    // Delete any existing interval
                    if (orologio_statistiche_recenti) {

                        // You could add a return here instead...
                        clearInterval(orologio_statistiche_recenti);
                    }


                    orologio_statistiche_recenti = setInterval(function() {

                        if (statistiche_recenti_storico == 0) {

                            // @BUG
                            // You were setting this to 1 after the first interval
                            // thus subsequent calls to this were not triggering the alert.

                            // statistiche_recenti_storico = 1;
                            alert('end');
                            clearInterval(orologio_statistiche_recenti); 
                        }
                    }, 5000);
                }


                $('#ok').on('click', startInterval);

                //Start your interval, by invoking the function
                startInterval();

            })();
        </script>
    </body>
</html>
0 голосов
/ 25 октября 2018
var statistiche_recenti_storico = 0;
    var orologio_statistiche_recenti;
    var intervalFn=function() {
      if (statistiche_recenti_storico == 0) {
        statistiche_recenti_storico = 1;
        alert('end');
        clearInterval(orologio_statistiche_recenti); 
      }
    }
    orologio_statistiche_recenti = setInterval(intervalFn, 5000);


    $('#ok').on('click', function(){
        // ????
      setInterval(intervalFn, 5000);
    });

Создайте ее как отдельную функцию и снова вызовите, используя setInterval(functionName, interval), куда хотите.

...