source

60초마다 함수를 호출하다

itover 2022. 12. 11. 10:20
반응형

60초마다 함수를 호출하다

사용.setTimeout()지정된 시간에 기능을 시작할 수 있습니다.

setTimeout(function, 60000);

하지만 이 기능을 여러 번 실행하려면 어떻게 해야 하나요?시간 간격이 경과할 때마다 (예를 들어 60초마다) 기능을 실행하고 싶습니다.

이 코드에 문제가 없다면timer는 간격보다 오래 걸릴 수 있습니다.다음 명령을 사용합니다.

setInterval(function, delay)

그러면 첫 번째 파라미터로 전달된 함수가 반복적으로 실행됩니다.

보다 나은 접근법은setTimeout와 함께self-executing anonymous기능:

(function(){
    // do some stuff
    setTimeout(arguments.callee, 60000);
})();

그 때문에, 코드가 실행되기 전에 다음의 콜이 발신되지 않게 됩니다.나는 사용했다arguments.callee이 예에서는 함수 참조로 사용합니다.함수에 이름을 붙이고 호출하는 것이 더 좋은 방법입니다.setTimeout왜냐면arguments.calleeecmascript 5에서는 권장되지 않습니다.

를 사용하다

setInterval(function, 60000);

EDIT : (클럭 시작 후 클럭을 정지하는 경우)

[스크립트(Script)]섹션

<script>
var int=self.setInterval(function, 60000);
</script>

및 HTML 코드

<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>

jandy답변을 보다 효율적으로 사용하여 모든 데이터를 폴링하는 폴링 기능을 구현합니다.intervalseconds(초) 및 그 후 종료됩니다.timeout초수

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000;

    (function p() {
        fn();
        if (((new Date).getTime() - startTime ) <= timeout)  {
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

갱신하다

코멘트에 따라서, 폴링을 정지하는 전달된 함수의 기능에 대해서, 코멘트를 갱신합니다.

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000,
    canPoll = true;

    (function p() {
        canPoll = ((new Date).getTime() - startTime ) <= timeout;
        if (!fn() && canPoll)  { // ensures the function exucutes
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

function sendHeartBeat(params) {
    ...
    ...
    if (receivedData) {
        // no need to execute further
        return true; // or false, change the IIFE inside condition accordingly.
    }
}

jQuery에서는 다음과 같이 할 수 있습니다.

function random_no(){
     var ran=Math.random();
     jQuery('#random_no_container').html(ran);
}
           
window.setInterval(function(){
       /// call your function here
      random_no();
}, 6000);  // Change Interval here to test. For eg: 5000 for 5 sec
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="random_no_container">
      Hello. Here you can see random numbers after every 6 sec
</div>

setInterval(fn,time)

당신이 추구하는 방법이에요

함수의 마지막에 set Timeout을 호출하기만 하면 됩니다.그러면 이벤트 큐에 다시 추가됩니다.모든 종류의 로직을 사용하여 지연값을 변경할 수 있습니다.예를들면,

function multiStep() {
  // do some work here
  blah_blah_whatever();
  var newtime = 60000;
  if (!requestStop) {
    setTimeout(multiStep, newtime);
  }
}

를 사용합니다.

Javascript 함수를 2초마다 10초간 연속 호출합니다.

var intervalPromise;
$scope.startTimer = function(fn, delay, timeoutTime) {
    intervalPromise = $interval(function() {
        fn();
        var currentTime = new Date().getTime() - $scope.startTime;
        if (currentTime > timeoutTime){
            $interval.cancel(intervalPromise);
          }                  
    }, delay);
};

$scope.startTimer(hello, 2000, 10000);

hello(){
  console.log("hello");
}

서브스크라이브의 좋은 예setInterval(), 및 를 사용합니다.clearInterval()영속 루프를 정지합니다.

function myTimer() {

}

var timer = setInterval(myTimer, 5000);

다음 회선을 호출하여 루프를 정지합니다.

clearInterval(timer);

function random(number) {
  return Math.floor(Math.random() * (number+1));
}
setInterval(() => {
    const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';//rgb value (0-255,0-255,0-255)
    document.body.style.backgroundColor = rndCol;   
}, 1000);
<script src="test.js"></script>
it changes background color in every 1 second (written as 1000 in JS)

// example:
// checkEach(1000, () => {
//   if(!canIDoWorkNow()) {
//     return true // try again after 1 second
//   }
//
//   doWork()
// })
export function checkEach(milliseconds, fn) {
  const timer = setInterval(
    () => {
      try {
        const retry = fn()

        if (retry !== true) {
          clearInterval(timer)
        }
      } catch (e) {
        clearInterval(timer)

        throw e
      }
    },
    milliseconds
  )
}

여기서는 자연수 0에서 ......n(60초마다 콘솔에서 다음 번호를 인쇄)을 콘솔합니다.setInterval()

var count = 0;
function abc(){
    count ++;
    console.log(count);
}
setInterval(abc,60*1000);

반복하여 기능에 매개 변수를 전달해야 하는 경우 여기에 언급되지 않았습니다.setTimeout(myFunc(myVal), 60000);는, 이전의 콜이 완료되기 전에, 콜 기능의 에러를 발생시킵니다.

따라서 다음과 같이 매개 변수를 전달할 수 있습니다.

setTimeout(function () {
            myFunc(myVal);
        }, 60000)

자세한 내용은 JavaScript 정원을 참조하십시오.

도움이 됐으면 좋겠네요

이 명령어를 호출하는 루프 함수를 포함하는 함수를 호출하는 것을 선호합니다.setTimeout일정한 간격으로 스스로요.

function timer(interval = 1000) {
  function loop(count = 1) {
    console.log(count);
    setTimeout(loop, interval, ++count);
  }
  loop();
}

timer();

전화를 거는 방법은 두 가지가 있습니다.

  1. setInterval(function (){ functionName();}, 60000);

  2. setInterval(functionName, 60000);

위의 함수는 60초마다 호출됩니다.

언급URL : https://stackoverflow.com/questions/3138756/calling-a-function-every-60-seconds

반응형