Reputation: 739
I have 4 sorting algorithms which I want to visualize. I want to make them run at the same time. Should I write functions like bubbleSortStep
instead of just bubbleSort
to call it every second for example and execute one step. For example like this:
setInterval(() => {
bubbleSortStep()
insertionSortStep()
quicksortStep()
}, 1000)
Or is it going to work fine if I create the sorting functions the normal way and add an interval to each of them like:
bubbleSort() {
setInterval(() => {
// sorting...
}, 1000)
}
...same for other three, and call them afterwards.
bubblesort()
insertionSort()
quicksort()
The idea is coming from YouTube videos like this where the colors change all at once.
Upvotes: 1
Views: 48
Reputation: 371019
JS timer functions are not all that precise. If each different algorithm initializes a different timer, it might be an issue; they might get out of sync. (If you were using recursive setTimeout
s, I know they'd definitely eventually get out of sync if the process took a long time.) Setting just a single timer and running one step for each algorithm inside that timer is probably a more trustworthy approach.
Note that the syntax you'll need will be something like
setInterval(() => {
bubbleSortStep()
insertionSortStep()
quicksortStep()
}, 1000)
(setInterval
accepts a function, not an object)
Upvotes: 2