HEX
Server: Apache
System: Linux server11 5.10.0-33-amd64 #1 SMP Debian 5.10.226-1 (2024-10-03) x86_64
User: web78 (5081)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/clients/client1/web78/web/wp-content/plugins/jetpack/extensions/shared/use-ref-interval.ts
import { useCallback, useEffect, useRef } from '@wordpress/element';

interface RafHandle {
	id: number;
}

const setRafInterval = ( callback: () => void, timeout: number = 0 ) => {
	const interval = timeout < 0 ? 0 : timeout;
	const handle: RafHandle = {
		id: 0,
	};

	let startTime = Date.now();

	const loop = () => {
		const nowTime = Date.now();
		if ( nowTime - startTime >= interval ) {
			startTime = nowTime;
			callback();
		}

		handle.id = requestAnimationFrame( loop );
	};

	handle.id = requestAnimationFrame( loop );

	return handle;
};

const clearRafInterval = ( handle?: RafHandle | null ) => {
	if ( handle ) {
		cancelAnimationFrame( handle.id );
	}
};

/**
 * Invoke a function on an interval that uses requestAnimationFrame.
 *
 * @param {Function} callback - Function to invoke
 * @param {number} timeout - Interval timout in MS.
 *
 * @returns {Function} Function to clear the interval.
 */
const useRafInterval = ( callback: () => void, timeout = 0 ) => {
	const timerRef = useRef< RafHandle >();

	const callbackRef = useRef( callback );
	callbackRef.current = callback;

	useEffect( () => {
		timerRef.current = setRafInterval( () => {
			callbackRef.current();
		}, timeout );

		return () => {
			clearRafInterval( timerRef.current );
		};
	}, [ timeout ] );

	const clear = useCallback( () => {
		clearRafInterval( timerRef.current );
	}, [] );

	return clear;
};

export default useRafInterval;