Создайте функцию и вызовите ее в своем коде, что является жизнеспособным подходом.
Я обернул ваш код в 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>