JSFiddle - React, Tailwind, and code Playground

by Augustus Yuan

HTML

<div id="area">

</div>

JavaScript

/*
 * mySetInterval and myClearInterval
 *
 * These helper functions recreate the native implementation
 * of setInterval in the browser by using a recursive setTimeout and
 * constantly keeping track of the relevant setTimeout id. If a user
 * calls myClearInterval, it should stop the current timeout and stop
 * the interval appropriately and then block that interval id from being
 * set again.
 */

/*
 * currentIntervals represents the pool of interval ids that are currently
 * being run. Each interval's id is the corresponding index in the array
 * with its value being the current timeoutId that is running.
 *
 * NOTE because MDN specifies the index of setInterval returns a
 * a non-zero index, I decided to utilize this space to keep track of the
 * number of intervals running (felt it might be useful) which is why it
 * is instantiated with 0.
 *
 * Please also note MDN documentation also mentions that the pool of interval ids
 * and timeout ids is shared in the native implementation. I did not want to
 * overcomplicate this so this simply
 */
var currentIntervals = [0];

/**
 * mySetInterval
 *
 * function that when called will trigger a recurisve setTimeout to constantly
 * call the function passed in after duration in milliseconds. If the interval
 * has not been cleared, a new timeout will start and update the currentIntervals
 * with the new timeout. This function will return the corresponding intervalId
 * that you must keep track of in order to clear the interval.
 *
 * @param {Function} func
 * @param {number} duration
 * @return {number} intervalId
 */
function mySetInterval(func, duration) {
  if (typeof func !== "function") {
    throw new Error("Please specify a valid function.");
  }
  if (typeof duration !== "number") {
    throw new Error("Please specify a valid number for duration");
  }
  var args = Array.prototype.slice.call(arguments, 2);
  currentIntervals.push(-1); // reserve space for setTimeout
  currentIntervals[0]++;
  var timeoutId =...